(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("babylonjs", [], factory); else if(typeof exports === 'object') exports["babylonjs"] = factory(); else root["BABYLON"] = factory(); })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), 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 = "./Legacy/legacy.ts"); /******/ }) /************************************************************************/ /******/ ({ /***/ "../node_modules/tslib/tslib.es6.js": /*!******************************************!*\ !*** ../node_modules/tslib/tslib.es6.js ***! \******************************************/ /*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__createBinding", function() { return __createBinding; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldGet", function() { return __classPrivateFieldGet; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldSet", function() { return __classPrivateFieldSet; }); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise */ 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 (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(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); } function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; } function __decorate(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 __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var __createBinding = Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; }); function __exportStar(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __spreadArrays() { 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; }; function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; var __setModuleDefault = Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } function __classPrivateFieldGet(receiver, privateMap) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return privateMap.get(receiver); } function __classPrivateFieldSet(receiver, privateMap, value) { if (!privateMap.has(receiver)) { throw new TypeError("attempted to set private field on non-instance"); } privateMap.set(receiver, value); return value; } /***/ }), /***/ "../node_modules/webpack/buildin/global.js": /*!*************************************************!*\ !*** ../node_modules/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/abstractActionManager.ts": /*!******************************************!*\ !*** ./Actions/abstractActionManager.ts ***! \******************************************/ /*! exports provided: AbstractActionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AbstractActionManager", function() { return AbstractActionManager; }); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * Abstract class used to decouple action Manager from scene and meshes. * Do not instantiate. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var AbstractActionManager = /** @class */ (function () { function AbstractActionManager() { /** Gets the cursor to use when hovering items */ this.hoverCursor = ''; /** Gets the list of actions */ this.actions = new Array(); /** * Gets or sets a boolean indicating that the manager is recursive meaning that it can trigger action from children */ this.isRecursive = false; } Object.defineProperty(AbstractActionManager, "HasTriggers", { /** * Does exist one action manager with at least one trigger **/ get: function () { for (var t in AbstractActionManager.Triggers) { if (AbstractActionManager.Triggers.hasOwnProperty(t)) { return true; } } return false; }, enumerable: false, configurable: true }); Object.defineProperty(AbstractActionManager, "HasPickTriggers", { /** * Does exist one action manager with at least one pick trigger **/ get: function () { for (var t in AbstractActionManager.Triggers) { if (AbstractActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int >= _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].ACTION_OnPickTrigger && t_int <= _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].ACTION_OnPickUpTrigger) { return true; } } } return false; }, enumerable: false, configurable: true }); /** * Does exist one action manager that handles actions of a given trigger * @param trigger defines the trigger to be tested * @return a boolean indicating whether the trigger is handeled by at least one action manager **/ AbstractActionManager.HasSpecificTrigger = function (trigger) { for (var t in AbstractActionManager.Triggers) { if (AbstractActionManager.Triggers.hasOwnProperty(t)) { var t_int = parseInt(t); if (t_int === trigger) { return true; } } } return false; }; /** Gets the list of active triggers */ AbstractActionManager.Triggers = {}; return AbstractActionManager; }()); /***/ }), /***/ "./Actions/action.ts": /*!***************************!*\ !*** ./Actions/action.ts ***! \***************************/ /*! exports provided: Action */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return Action; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * The action to be carried out following a trigger * @see https://doc.babylonjs.com/how_to/how_to_use_actions#available-actions */ var Action = /** @class */ (function () { /** * Creates a new Action * @param triggerOptions the trigger, with or without parameters, for the action * @param condition an optional determinant of action */ function Action( /** the trigger, with or without parameters, for the action */ triggerOptions, condition) { this.triggerOptions = triggerOptions; /** * An event triggered prior to action being executed. */ this.onBeforeExecuteObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); if (triggerOptions.parameter) { this.trigger = triggerOptions.trigger; this._triggerParameter = triggerOptions.parameter; } else if (triggerOptions.trigger) { this.trigger = triggerOptions.trigger; } else { this.trigger = triggerOptions; } this._nextActiveAction = this; this._condition = condition; } /** * Internal only * @hidden */ Action.prototype._prepare = function () { }; /** * Gets the trigger parameters * @returns the trigger parameters */ Action.prototype.getTriggerParameter = function () { return this._triggerParameter; }; /** * Internal only - executes current action event * @hidden */ Action.prototype._executeCurrent = function (evt) { if (this._nextActiveAction._condition) { var condition = this._nextActiveAction._condition; var currentRenderId = this._actionManager.getScene().getRenderId(); // We cache the current evaluation for the current frame if (condition._evaluationId === currentRenderId) { if (!condition._currentResult) { return; } } else { condition._evaluationId = currentRenderId; if (!condition.isValid()) { condition._currentResult = false; return; } condition._currentResult = true; } } this.onBeforeExecuteObservable.notifyObservers(this); this._nextActiveAction.execute(evt); this.skipToNextActiveAction(); }; /** * Execute placeholder for child classes * @param evt optional action event */ Action.prototype.execute = function (evt) { }; /** * Skips to next active action */ Action.prototype.skipToNextActiveAction = function () { if (this._nextActiveAction._child) { if (!this._nextActiveAction._child._actionManager) { this._nextActiveAction._child._actionManager = this._actionManager; } this._nextActiveAction = this._nextActiveAction._child; } else { this._nextActiveAction = this; } }; /** * Adds action to chain of actions, may be a DoNothingAction * @param action defines the next action to execute * @returns The action passed in * @see https://www.babylonjs-playground.com/#1T30HR#0 */ Action.prototype.then = function (action) { this._child = action; action._actionManager = this._actionManager; action._prepare(); return action; }; /** * Internal only * @hidden */ Action.prototype._getProperty = function (propertyPath) { return this._actionManager._getProperty(propertyPath); }; /** * Internal only * @hidden */ Action.prototype._getEffectiveTarget = function (target, propertyPath) { return this._actionManager._getEffectiveTarget(target, propertyPath); }; /** * Serialize placeholder for child classes * @param parent of child * @returns the serialized object */ Action.prototype.serialize = function (parent) { }; /** * Internal only called by serialize * @hidden */ Action.prototype._serialize = function (serializedAction, parent) { var serializationObject = { type: 1, children: [], name: serializedAction.name, properties: serializedAction.properties || [] }; // Serialize child if (this._child) { this._child.serialize(serializationObject); } // Check if "this" has a condition if (this._condition) { var serializedCondition = this._condition.serialize(); serializedCondition.children.push(serializationObject); if (parent) { parent.children.push(serializedCondition); } return serializedCondition; } if (parent) { parent.children.push(serializationObject); } return serializationObject; }; /** * Internal only * @hidden */ Action._SerializeValueAsString = function (value) { if (typeof value === "number") { return value.toString(); } if (typeof value === "boolean") { return value ? "true" : "false"; } if (value instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector2"]) { return value.x + ", " + value.y; } if (value instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]) { return value.x + ", " + value.y + ", " + value.z; } if (value instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"]) { return value.r + ", " + value.g + ", " + value.b; } if (value instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color4"]) { return value.r + ", " + value.g + ", " + value.b + ", " + value.a; } return value; // string }; /** * Internal only * @hidden */ Action._GetTargetProperty = function (target) { return { name: "target", targetType: target._isMesh ? "MeshProperties" : target._isLight ? "LightProperties" : target._isCamera ? "CameraProperties" : "SceneProperties", value: target._isScene ? "Scene" : target.name }; }; return Action; }()); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.Action"] = Action; /***/ }), /***/ "./Actions/actionEvent.ts": /*!********************************!*\ !*** ./Actions/actionEvent.ts ***! \********************************/ /*! exports provided: ActionEvent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return ActionEvent; }); /** * ActionEvent is the event being sent when an action is triggered. */ var ActionEvent = /** @class */ (function () { /** * Creates a new ActionEvent * @param source The mesh or sprite that triggered the action * @param pointerX The X mouse cursor position at the time of the event * @param pointerY The Y mouse cursor position at the time of the event * @param meshUnderPointer The mesh that is currently pointed at (can be null) * @param sourceEvent the original (browser) event that triggered the ActionEvent * @param additionalData additional data for the event */ function ActionEvent( /** The mesh or sprite that triggered the action */ source, /** The X mouse cursor position at the time of the event */ pointerX, /** The Y mouse cursor position at the time of the event */ pointerY, /** The mesh that is currently pointed at (can be null) */ meshUnderPointer, /** the original (browser) event that triggered the ActionEvent */ sourceEvent, /** additional data for the event */ additionalData) { this.source = source; this.pointerX = pointerX; this.pointerY = pointerY; this.meshUnderPointer = meshUnderPointer; this.sourceEvent = sourceEvent; this.additionalData = additionalData; } /** * Helper function to auto-create an ActionEvent from a source mesh. * @param source The source mesh that triggered the event * @param evt The original (browser) event * @param additionalData additional data for the event * @returns the new ActionEvent */ ActionEvent.CreateNew = function (source, evt, additionalData) { var scene = source.getScene(); return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer || source, evt, additionalData); }; /** * Helper function to auto-create an ActionEvent from a source sprite * @param source The source sprite that triggered the event * @param scene Scene associated with the sprite * @param evt The original (browser) event * @param additionalData additional data for the event * @returns the new ActionEvent */ ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) { return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData); }; /** * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew * @param scene the scene where the event occurred * @param evt The original (browser) event * @returns the new ActionEvent */ ActionEvent.CreateNewFromScene = function (scene, evt) { return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt); }; /** * Helper function to auto-create an ActionEvent from a primitive * @param prim defines the target primitive * @param pointerPos defines the pointer position * @param evt The original (browser) event * @param additionalData additional data for the event * @returns the new ActionEvent */ ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) { return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData); }; return ActionEvent; }()); /***/ }), /***/ "./Actions/actionManager.ts": /*!**********************************!*\ !*** ./Actions/actionManager.ts ***! \**********************************/ /*! exports provided: ActionManager */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return ActionManager; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts"); /* harmony import */ var _condition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./condition */ "./Actions/condition.ts"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _directActions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directActions */ "./Actions/directActions.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _abstractActionManager__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./abstractActionManager */ "./Actions/abstractActionManager.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /** * Action Manager manages all events to be triggered on a given mesh or the global scene. * A single scene can have many Action Managers to handle predefined actions on specific meshes. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var ActionManager = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ActionManager, _super); /** * Creates a new action manager * @param scene defines the hosting scene */ function ActionManager(scene) { var _this = _super.call(this) || this; _this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene; scene.actionManagers.push(_this); return _this; } // Methods /** * Releases all associated resources */ ActionManager.prototype.dispose = function () { var index = this._scene.actionManagers.indexOf(this); for (var i = 0; i < this.actions.length; i++) { var action = this.actions[i]; ActionManager.Triggers[action.trigger]--; if (ActionManager.Triggers[action.trigger] === 0) { delete ActionManager.Triggers[action.trigger]; } } if (index > -1) { this._scene.actionManagers.splice(index, 1); } }; /** * Gets hosting scene * @returns the hosting scene */ ActionManager.prototype.getScene = function () { return this._scene; }; /** * Does this action manager handles actions of any of the given triggers * @param triggers defines the triggers to be tested * @return a boolean indicating whether one (or more) of the triggers is handled */ ActionManager.prototype.hasSpecificTriggers = function (triggers) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (triggers.indexOf(action.trigger) > -1) { return true; } } return false; }; /** * Does this action manager handles actions of any of the given triggers. This function takes two arguments for * speed. * @param triggerA defines the trigger to be tested * @param triggerB defines the trigger to be tested * @return a boolean indicating whether one (or more) of the triggers is handled */ ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (triggerA == action.trigger || triggerB == action.trigger) { return true; } } return false; }; /** * Does this action manager handles actions of a given trigger * @param trigger defines the trigger to be tested * @param parameterPredicate defines an optional predicate to filter triggers by parameter * @return whether the trigger is handled */ ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger === trigger) { if (parameterPredicate) { if (parameterPredicate(action.getTriggerParameter())) { return true; } } else { return true; } } } return false; }; Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", { /** * Does this action manager has pointer triggers */ get: function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) { return true; } } return false; }, enumerable: false, configurable: true }); Object.defineProperty(ActionManager.prototype, "hasPickTriggers", { /** * Does this action manager has pick triggers */ get: function () { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) { return true; } } return false; }, enumerable: false, configurable: true }); /** * Registers an action to this action manager * @param action defines the action to be registered * @return the action amended (prepared) after registration */ ActionManager.prototype.registerAction = function (action) { if (action.trigger === ActionManager.OnEveryFrameTrigger) { if (this.getScene().actionManager !== this) { _Misc_logger__WEBPACK_IMPORTED_MODULE_7__["Logger"].Warn("OnEveryFrameTrigger can only be used with scene.actionManager"); return null; } } this.actions.push(action); if (ActionManager.Triggers[action.trigger]) { ActionManager.Triggers[action.trigger]++; } else { ActionManager.Triggers[action.trigger] = 1; } action._actionManager = this; action._prepare(); return action; }; /** * Unregisters an action to this action manager * @param action defines the action to be unregistered * @return a boolean indicating whether the action has been unregistered */ ActionManager.prototype.unregisterAction = function (action) { var index = this.actions.indexOf(action); if (index !== -1) { this.actions.splice(index, 1); ActionManager.Triggers[action.trigger] -= 1; if (ActionManager.Triggers[action.trigger] === 0) { delete ActionManager.Triggers[action.trigger]; } action._actionManager = null; return true; } return false; }; /** * Process a specific trigger * @param trigger defines the trigger to process * @param evt defines the event details to be processed */ ActionManager.prototype.processTrigger = function (trigger, evt) { for (var index = 0; index < this.actions.length; index++) { var action = this.actions[index]; if (action.trigger === trigger) { if (evt) { if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) { var parameter = action.getTriggerParameter(); if (parameter && parameter !== evt.sourceEvent.keyCode) { if (!parameter.toLowerCase) { continue; } var lowerCase = parameter.toLowerCase(); if (lowerCase !== evt.sourceEvent.key) { var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode; var actualkey = String.fromCharCode(unicode).toLowerCase(); if (actualkey !== lowerCase) { continue; } } } } } action._executeCurrent(evt); } } }; /** @hidden */ ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) { var properties = propertyPath.split("."); for (var index = 0; index < properties.length - 1; index++) { target = target[properties[index]]; } return target; }; /** @hidden */ ActionManager.prototype._getProperty = function (propertyPath) { var properties = propertyPath.split("."); return properties[properties.length - 1]; }; /** * Serialize this manager to a JSON object * @param name defines the property name to store this manager * @returns a JSON representation of this manager */ ActionManager.prototype.serialize = function (name) { var root = { children: new Array(), name: name, type: 3, properties: new Array() // Empty for root but required }; for (var i = 0; i < this.actions.length; i++) { var triggerObject = { type: 0, children: new Array(), name: ActionManager.GetTriggerName(this.actions[i].trigger), properties: new Array() }; var triggerOptions = this.actions[i].triggerOptions; if (triggerOptions && typeof triggerOptions !== "number") { if (triggerOptions.parameter instanceof Node) { triggerObject.properties.push(_action__WEBPACK_IMPORTED_MODULE_4__["Action"]._GetTargetProperty(triggerOptions.parameter)); } else { var parameter = {}; _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_8__["DeepCopier"].DeepCopy(triggerOptions.parameter, parameter, ["mesh"]); if (triggerOptions.parameter && triggerOptions.parameter.mesh) { parameter._meshId = triggerOptions.parameter.mesh.id; } triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter }); } } // Serialize child action, recursively this.actions[i].serialize(triggerObject); // Add serialized trigger root.children.push(triggerObject); } return root; }; /** * Creates a new ActionManager from a JSON data * @param parsedActions defines the JSON data to read from * @param object defines the hosting mesh * @param scene defines the hosting scene */ ActionManager.Parse = function (parsedActions, object, scene) { var actionManager = new ActionManager(scene); if (object === null) { scene.actionManager = actionManager; } else { object.actionManager = actionManager; } // instanciate a new object var instanciate = function (name, params) { var internalClassType = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_9__["_TypeStore"].GetClass("BABYLON." + name); if (internalClassType) { var newInstance = Object.create(internalClassType.prototype); newInstance.constructor.apply(newInstance, params); return newInstance; } }; var parseParameter = function (name, value, target, propertyPath) { if (propertyPath === null) { // String, boolean or float var floatValue = parseFloat(value); if (value === "true" || value === "false") { return value === "true"; } else { return isNaN(floatValue) ? value : floatValue; } } var effectiveTarget = propertyPath.split("."); var values = value.split(","); // Get effective Target for (var i = 0; i < effectiveTarget.length; i++) { target = target[effectiveTarget[i]]; } // Return appropriate value with its type if (typeof (target) === "boolean") { return values[0] === "true"; } if (typeof (target) === "string") { return values[0]; } // Parameters with multiple values such as Vector3 etc. var split = new Array(); for (var i = 0; i < values.length; i++) { split.push(parseFloat(values[i])); } if (target instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArray(split); } if (target instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector4"]) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector4"].FromArray(split); } if (target instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"]) { return _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"].FromArray(split); } if (target instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color4"]) { return _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color4"].FromArray(split); } return parseFloat(values[0]); }; // traverse graph per trigger var traverse = function (parsedAction, trigger, condition, action, combineArray) { if (combineArray === void 0) { combineArray = null; } if (parsedAction.detached) { return; } var parameters = new Array(); var target = null; var propertyPath = null; var combine = parsedAction.combine && parsedAction.combine.length > 0; // Parameters if (parsedAction.type === 2) { parameters.push(actionManager); } else { parameters.push(trigger); } if (combine) { var actions = new Array(); for (var j = 0; j < parsedAction.combine.length; j++) { traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions); } parameters.push(actions); } else { for (var i = 0; i < parsedAction.properties.length; i++) { var value = parsedAction.properties[i].value; var name = parsedAction.properties[i].name; var targetType = parsedAction.properties[i].targetType; if (name === "target") { if (targetType !== null && targetType === "SceneProperties") { value = target = scene; } else { value = target = scene.getNodeByName(value); } } else if (name === "parent") { value = scene.getNodeByName(value); } else if (name === "sound") { // Can not externalize to component, so only checks for the presence off the API. if (scene.getSoundByName) { value = scene.getSoundByName(value); } } else if (name !== "propertyPath") { if (parsedAction.type === 2 && name === "operator") { value = _condition__WEBPACK_IMPORTED_MODULE_3__["ValueCondition"][value]; } else { value = parseParameter(name, value, target, name === "value" ? propertyPath : null); } } else { propertyPath = value; } parameters.push(value); } } if (combineArray === null) { parameters.push(condition); } else { parameters.push(null); } // If interpolate value action if (parsedAction.name === "InterpolateValueAction") { var param = parameters[parameters.length - 2]; parameters[parameters.length - 1] = param; parameters[parameters.length - 2] = condition; } // Action or condition(s) and not CombineAction var newAction = instanciate(parsedAction.name, parameters); if (newAction instanceof _condition__WEBPACK_IMPORTED_MODULE_3__["Condition"] && condition !== null) { var nothing = new _directActions__WEBPACK_IMPORTED_MODULE_5__["DoNothingAction"](trigger, condition); if (action) { action.then(nothing); } else { actionManager.registerAction(nothing); } action = nothing; } if (combineArray === null) { if (newAction instanceof _condition__WEBPACK_IMPORTED_MODULE_3__["Condition"]) { condition = newAction; newAction = action; } else { condition = null; if (action) { action.then(newAction); } else { actionManager.registerAction(newAction); } } } else { combineArray.push(newAction); } for (var i = 0; i < parsedAction.children.length; i++) { traverse(parsedAction.children[i], trigger, condition, newAction, null); } }; // triggers for (var i = 0; i < parsedActions.children.length; i++) { var triggerParams; var trigger = parsedActions.children[i]; if (trigger.properties.length > 0) { var param = trigger.properties[0].value; var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param); if (value._meshId) { value.mesh = scene.getMeshByID(value._meshId); } triggerParams = { trigger: ActionManager[trigger.name], parameter: value }; } else { triggerParams = ActionManager[trigger.name]; } for (var j = 0; j < trigger.children.length; j++) { if (!trigger.detached) { traverse(trigger.children[j], triggerParams, null, null); } } } }; /** * Get a trigger name by index * @param trigger defines the trigger index * @returns a trigger name */ ActionManager.GetTriggerName = function (trigger) { switch (trigger) { case 0: return "NothingTrigger"; case 1: return "OnPickTrigger"; case 2: return "OnLeftPickTrigger"; case 3: return "OnRightPickTrigger"; case 4: return "OnCenterPickTrigger"; case 5: return "OnPickDownTrigger"; case 6: return "OnPickUpTrigger"; case 7: return "OnLongPressTrigger"; case 8: return "OnPointerOverTrigger"; case 9: return "OnPointerOutTrigger"; case 10: return "OnEveryFrameTrigger"; case 11: return "OnIntersectionEnterTrigger"; case 12: return "OnIntersectionExitTrigger"; case 13: return "OnKeyDownTrigger"; case 14: return "OnKeyUpTrigger"; case 15: return "OnPickOutTrigger"; default: return ""; } }; /** * Nothing * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.NothingTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_NothingTrigger; /** * On pick * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnPickTrigger; /** * On left pick * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnLeftPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnLeftPickTrigger; /** * On right pick * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnRightPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnRightPickTrigger; /** * On center pick * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnCenterPickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnCenterPickTrigger; /** * On pick down * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickDownTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnPickDownTrigger; /** * On double pick * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnDoublePickTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnDoublePickTrigger; /** * On pick up * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickUpTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnPickUpTrigger; /** * On pick out. * This trigger will only be raised if you also declared a OnPickDown * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPickOutTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnPickOutTrigger; /** * On long press * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnLongPressTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnLongPressTrigger; /** * On pointer over * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPointerOverTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnPointerOverTrigger; /** * On pointer out * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnPointerOutTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnPointerOutTrigger; /** * On every frame * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnEveryFrameTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnEveryFrameTrigger; /** * On intersection enter * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnIntersectionEnterTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnIntersectionEnterTrigger; /** * On intersection exit * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnIntersectionExitTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnIntersectionExitTrigger; /** * On key down * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnKeyDownTrigger = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ACTION_OnKeyDownTrigger; /** * On key up * @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers */ ActionManager.OnKeyUpTrigger = 15; return ActionManager; }(_abstractActionManager__WEBPACK_IMPORTED_MODULE_10__["AbstractActionManager"])); /***/ }), /***/ "./Actions/condition.ts": /*!******************************!*\ !*** ./Actions/condition.ts ***! \******************************/ /*! exports provided: Condition, ValueCondition, PredicateCondition, StateCondition */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return Condition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return ValueCondition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return PredicateCondition; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return StateCondition; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * A Condition applied to an Action */ var Condition = /** @class */ (function () { /** * Creates a new Condition * @param actionManager the manager of the action the condition is applied to */ function Condition(actionManager) { this._actionManager = actionManager; } /** * Check if the current condition is valid * @returns a boolean */ Condition.prototype.isValid = function () { return true; }; /** * Internal only * @hidden */ Condition.prototype._getProperty = function (propertyPath) { return this._actionManager._getProperty(propertyPath); }; /** * Internal only * @hidden */ Condition.prototype._getEffectiveTarget = function (target, propertyPath) { return this._actionManager._getEffectiveTarget(target, propertyPath); }; /** * Serialize placeholder for child classes * @returns the serialized object */ Condition.prototype.serialize = function () { }; /** * Internal only * @hidden */ Condition.prototype._serialize = function (serializedCondition) { return { type: 2, children: [], name: serializedCondition.name, properties: serializedCondition.properties }; }; return Condition; }()); /** * Defines specific conditional operators as extensions of Condition */ var ValueCondition = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ValueCondition, _super); /** * Creates a new ValueCondition * @param actionManager manager for the action the condition applies to * @param target for the action * @param propertyPath path to specify the property of the target the conditional operator uses * @param value the value compared by the conditional operator against the current value of the property * @param operator the conditional operator, default ValueCondition.IsEqual */ function ValueCondition(actionManager, target, /** path to specify the property of the target the conditional operator uses */ propertyPath, /** the value compared by the conditional operator against the current value of the property */ value, /** the conditional operator, default ValueCondition.IsEqual */ operator) { if (operator === void 0) { operator = ValueCondition.IsEqual; } var _this = _super.call(this, actionManager) || this; _this.propertyPath = propertyPath; _this.value = value; _this.operator = operator; _this._target = target; _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath); _this._property = _this._getProperty(_this.propertyPath); return _this; } Object.defineProperty(ValueCondition, "IsEqual", { /** * returns the number for IsEqual */ get: function () { return ValueCondition._IsEqual; }, enumerable: false, configurable: true }); Object.defineProperty(ValueCondition, "IsDifferent", { /** * Returns the number for IsDifferent */ get: function () { return ValueCondition._IsDifferent; }, enumerable: false, configurable: true }); Object.defineProperty(ValueCondition, "IsGreater", { /** * Returns the number for IsGreater */ get: function () { return ValueCondition._IsGreater; }, enumerable: false, configurable: true }); Object.defineProperty(ValueCondition, "IsLesser", { /** * Returns the number for IsLesser */ get: function () { return ValueCondition._IsLesser; }, enumerable: false, configurable: true }); /** * Compares the given value with the property value for the specified conditional operator * @returns the result of the comparison */ ValueCondition.prototype.isValid = function () { switch (this.operator) { case ValueCondition.IsGreater: return this._effectiveTarget[this._property] > this.value; case ValueCondition.IsLesser: return this._effectiveTarget[this._property] < this.value; case ValueCondition.IsEqual: case ValueCondition.IsDifferent: var check; if (this.value.equals) { check = this.value.equals(this._effectiveTarget[this._property]); } else { check = this.value === this._effectiveTarget[this._property]; } return this.operator === ValueCondition.IsEqual ? check : !check; } return false; }; /** * Serialize the ValueCondition into a JSON compatible object * @returns serialization object */ ValueCondition.prototype.serialize = function () { return this._serialize({ name: "ValueCondition", properties: [ _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.value) }, { name: "operator", value: ValueCondition.GetOperatorName(this.operator) } ] }); }; /** * Gets the name of the conditional operator for the ValueCondition * @param operator the conditional operator * @returns the name */ ValueCondition.GetOperatorName = function (operator) { switch (operator) { case ValueCondition._IsEqual: return "IsEqual"; case ValueCondition._IsDifferent: return "IsDifferent"; case ValueCondition._IsGreater: return "IsGreater"; case ValueCondition._IsLesser: return "IsLesser"; default: return ""; } }; /** * Internal only * @hidden */ ValueCondition._IsEqual = 0; /** * Internal only * @hidden */ ValueCondition._IsDifferent = 1; /** * Internal only * @hidden */ ValueCondition._IsGreater = 2; /** * Internal only * @hidden */ ValueCondition._IsLesser = 3; return ValueCondition; }(Condition)); /** * Defines a predicate condition as an extension of Condition */ var PredicateCondition = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PredicateCondition, _super); /** * Creates a new PredicateCondition * @param actionManager manager for the action the condition applies to * @param predicate defines the predicate function used to validate the condition */ function PredicateCondition(actionManager, /** defines the predicate function used to validate the condition */ predicate) { var _this = _super.call(this, actionManager) || this; _this.predicate = predicate; return _this; } /** * @returns the validity of the predicate condition */ PredicateCondition.prototype.isValid = function () { return this.predicate(); }; return PredicateCondition; }(Condition)); /** * Defines a state condition as an extension of Condition */ var StateCondition = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateCondition, _super); /** * Creates a new StateCondition * @param actionManager manager for the action the condition applies to * @param target of the condition * @param value to compare with target state */ function StateCondition(actionManager, target, /** Value to compare with target state */ value) { var _this = _super.call(this, actionManager) || this; _this.value = value; _this._target = target; return _this; } /** * Gets a boolean indicating if the current condition is met * @returns the validity of the state */ StateCondition.prototype.isValid = function () { return this._target.state === this.value; }; /** * Serialize the StateCondition into a JSON compatible object * @returns serialization object */ StateCondition.prototype.serialize = function () { return this._serialize({ name: "StateCondition", properties: [ _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), { name: "value", value: this.value } ] }); }; return StateCondition; }(Condition)); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.ValueCondition"] = ValueCondition; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.PredicateCondition"] = PredicateCondition; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.StateCondition"] = StateCondition; /***/ }), /***/ "./Actions/directActions.ts": /*!**********************************!*\ !*** ./Actions/directActions.ts ***! \**********************************/ /*! exports provided: SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return SwitchBooleanAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return SetStateAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return SetValueAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return IncrementValueAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return PlayAnimationAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return StopAnimationAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return DoNothingAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return CombineAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return ExecuteCodeAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return SetParentAction; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This defines an action responsible to toggle a boolean once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var SwitchBooleanAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SwitchBooleanAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the boolean * @param propertyPath defines the path to the boolean property in the target object * @param condition defines the trigger related conditions */ function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ SwitchBooleanAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; /** * Execute the action toggle the boolean value. */ SwitchBooleanAction.prototype.execute = function () { this._effectiveTarget[this._property] = !this._effectiveTarget[this._property]; }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SwitchBooleanAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SwitchBooleanAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath } ] }, parent); }; return SwitchBooleanAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to set a the state field of the target * to a desired value once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var SetStateAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SetStateAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the state property * @param value defines the value to store in the state field * @param condition defines the trigger related conditions */ function SetStateAction(triggerOptions, target, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.value = value; _this._target = target; return _this; } /** * Execute the action and store the value on the target state property. */ SetStateAction.prototype.execute = function () { this._target.state = this.value; }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SetStateAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetStateAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "value", value: this.value } ] }, parent); }; return SetStateAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to set a property of the target * to a desired value once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var SetValueAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SetValueAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the property * @param propertyPath defines the path of the property to set in the target * @param value defines the value to set in the property * @param condition defines the trigger related conditions */ function SetValueAction(triggerOptions, target, propertyPath, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ SetValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; /** * Execute the action and set the targetted property to the desired value. */ SetValueAction.prototype.execute = function () { this._effectiveTarget[this._property] = this.value; if (this._target.markAsDirty) { this._target.markAsDirty(this._property); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SetValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetValueAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.value) } ] }, parent); }; return SetValueAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to increment the target value * to a desired value once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var IncrementValueAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(IncrementValueAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the property * @param propertyPath defines the path of the property to increment in the target * @param value defines the value value we should increment the property by * @param condition defines the trigger related conditions */ function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.propertyPath = propertyPath; _this.value = value; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ IncrementValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); if (typeof this._effectiveTarget[this._property] !== "number") { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Warning: IncrementValueAction can only be used with number values"); } }; /** * Execute the action and increment the target of the value amount. */ IncrementValueAction.prototype.execute = function () { this._effectiveTarget[this._property] += this.value; if (this._target.markAsDirty) { this._target.markAsDirty(this._property); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ IncrementValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "IncrementValueAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.value) } ] }, parent); }; return IncrementValueAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to start an animation once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var PlayAnimationAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PlayAnimationAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the target animation or animation name * @param from defines from where the animation should start (animation frame) * @param end defines where the animation should stop (animation frame) * @param loop defines if the animation should loop or stop after the first play * @param condition defines the trigger related conditions */ function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.from = from; _this.to = to; _this.loop = loop; _this._target = target; return _this; } /** @hidden */ PlayAnimationAction.prototype._prepare = function () { }; /** * Execute the action and play the animation. */ PlayAnimationAction.prototype.execute = function () { var scene = this._actionManager.getScene(); scene.beginAnimation(this._target, this.from, this.to, this.loop); }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ PlayAnimationAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "PlayAnimationAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), { name: "from", value: String(this.from) }, { name: "to", value: String(this.to) }, { name: "loop", value: _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._SerializeValueAsString(this.loop) || false } ] }, parent); }; return PlayAnimationAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to stop an animation once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var StopAnimationAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StopAnimationAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the target animation or animation name * @param condition defines the trigger related conditions */ function StopAnimationAction(triggerOptions, target, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._target = target; return _this; } /** @hidden */ StopAnimationAction.prototype._prepare = function () { }; /** * Execute the action and stop the animation. */ StopAnimationAction.prototype.execute = function () { var scene = this._actionManager.getScene(); scene.stopAnimation(this._target); }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ StopAnimationAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "StopAnimationAction", properties: [_action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target)] }, parent); }; return StopAnimationAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible that does nothing once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var DoNothingAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DoNothingAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param condition defines the trigger related conditions */ function DoNothingAction(triggerOptions, condition) { if (triggerOptions === void 0) { triggerOptions = _Engines_constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].ACTION_NothingTrigger; } return _super.call(this, triggerOptions, condition) || this; } /** * Execute the action and do nothing. */ DoNothingAction.prototype.execute = function () { }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ DoNothingAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "DoNothingAction", properties: [] }, parent); }; return DoNothingAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to trigger several actions once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var CombineAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CombineAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param children defines the list of aggregated animations to run * @param condition defines the trigger related conditions */ function CombineAction(triggerOptions, children, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.children = children; return _this; } /** @hidden */ CombineAction.prototype._prepare = function () { for (var index = 0; index < this.children.length; index++) { this.children[index]._actionManager = this._actionManager; this.children[index]._prepare(); } }; /** * Execute the action and executes all the aggregated actions. */ CombineAction.prototype.execute = function (evt) { for (var index = 0; index < this.children.length; index++) { this.children[index].execute(evt); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ CombineAction.prototype.serialize = function (parent) { var serializationObject = _super.prototype._serialize.call(this, { name: "CombineAction", properties: [], combine: [] }, parent); for (var i = 0; i < this.children.length; i++) { serializationObject.combine.push(this.children[i].serialize(null)); } return serializationObject; }; return CombineAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to run code (external event) once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var ExecuteCodeAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExecuteCodeAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param func defines the callback function to run * @param condition defines the trigger related conditions */ function ExecuteCodeAction(triggerOptions, func, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this.func = func; return _this; } /** * Execute the action and run the attached code. */ ExecuteCodeAction.prototype.execute = function (evt) { this.func(evt); }; return ExecuteCodeAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); /** * This defines an action responsible to set the parent property of the target once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var SetParentAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SetParentAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the target containing the parent property * @param parent defines from where the animation should start (animation frame) * @param condition defines the trigger related conditions */ function SetParentAction(triggerOptions, target, parent, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._target = target; _this._parent = parent; return _this; } /** @hidden */ SetParentAction.prototype._prepare = function () { }; /** * Execute the action and set the parent property. */ SetParentAction.prototype.execute = function () { if (this._target.parent === this._parent) { return; } var invertParentWorldMatrix = this._parent.getWorldMatrix().clone(); invertParentWorldMatrix.invert(); this._target.position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this._target.position, invertParentWorldMatrix); this._target.parent = this._parent; }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ SetParentAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "SetParentAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._target), _action__WEBPACK_IMPORTED_MODULE_3__["Action"]._GetTargetProperty(this._parent), ] }, parent); }; return SetParentAction; }(_action__WEBPACK_IMPORTED_MODULE_3__["Action"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetParentAction"] = SetParentAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.ExecuteCodeAction"] = ExecuteCodeAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.DoNothingAction"] = DoNothingAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.StopAnimationAction"] = StopAnimationAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.PlayAnimationAction"] = PlayAnimationAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.IncrementValueAction"] = IncrementValueAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetValueAction"] = SetValueAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetStateAction"] = SetStateAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SetParentAction"] = SetParentAction; /***/ }), /***/ "./Actions/directAudioActions.ts": /*!***************************************!*\ !*** ./Actions/directAudioActions.ts ***! \***************************************/ /*! exports provided: PlaySoundAction, StopSoundAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return PlaySoundAction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return StopSoundAction; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This defines an action helpful to play a defined sound on a triggered action. */ var PlaySoundAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PlaySoundAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param sound defines the sound to play * @param condition defines the trigger related conditions */ function PlaySoundAction(triggerOptions, sound, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._sound = sound; return _this; } /** @hidden */ PlaySoundAction.prototype._prepare = function () { }; /** * Execute the action and play the sound. */ PlaySoundAction.prototype.execute = function () { if (this._sound !== undefined) { this._sound.play(); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ PlaySoundAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "PlaySoundAction", properties: [{ name: "sound", value: this._sound.name }] }, parent); }; return PlaySoundAction; }(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); /** * This defines an action helpful to stop a defined sound on a triggered action. */ var StopSoundAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StopSoundAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param sound defines the sound to stop * @param condition defines the trigger related conditions */ function StopSoundAction(triggerOptions, sound, condition) { var _this = _super.call(this, triggerOptions, condition) || this; _this._sound = sound; return _this; } /** @hidden */ StopSoundAction.prototype._prepare = function () { }; /** * Execute the action and stop the sound. */ StopSoundAction.prototype.execute = function () { if (this._sound !== undefined) { this._sound.stop(); } }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ StopSoundAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "StopSoundAction", properties: [{ name: "sound", value: this._sound.name }] }, parent); }; return StopSoundAction; }(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.PlaySoundAction"] = StopSoundAction; _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.StopSoundAction"] = StopSoundAction; /***/ }), /***/ "./Actions/index.ts": /*!**************************!*\ !*** ./Actions/index.ts ***! \**************************/ /*! exports provided: AbstractActionManager, Action, ActionEvent, ActionManager, Condition, ValueCondition, PredicateCondition, StateCondition, SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction, PlaySoundAction, StopSoundAction, InterpolateValueAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _abstractActionManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./abstractActionManager */ "./Actions/abstractActionManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractActionManager", function() { return _abstractActionManager__WEBPACK_IMPORTED_MODULE_0__["AbstractActionManager"]; }); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return _action__WEBPACK_IMPORTED_MODULE_1__["Action"]; }); /* harmony import */ var _actionEvent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./actionEvent */ "./Actions/actionEvent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return _actionEvent__WEBPACK_IMPORTED_MODULE_2__["ActionEvent"]; }); /* harmony import */ var _actionManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./actionManager */ "./Actions/actionManager.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return _actionManager__WEBPACK_IMPORTED_MODULE_3__["ActionManager"]; }); /* harmony import */ var _condition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./condition */ "./Actions/condition.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return _condition__WEBPACK_IMPORTED_MODULE_4__["Condition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_4__["ValueCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_4__["PredicateCondition"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return _condition__WEBPACK_IMPORTED_MODULE_4__["StateCondition"]; }); /* harmony import */ var _directActions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./directActions */ "./Actions/directActions.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["SwitchBooleanAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["SetStateAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["SetValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["IncrementValueAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["PlayAnimationAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["StopAnimationAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["DoNothingAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["CombineAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["ExecuteCodeAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return _directActions__WEBPACK_IMPORTED_MODULE_5__["SetParentAction"]; }); /* harmony import */ var _directAudioActions__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./directAudioActions */ "./Actions/directAudioActions.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return _directAudioActions__WEBPACK_IMPORTED_MODULE_6__["PlaySoundAction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return _directAudioActions__WEBPACK_IMPORTED_MODULE_6__["StopSoundAction"]; }); /* harmony import */ var _interpolateValueAction__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./interpolateValueAction */ "./Actions/interpolateValueAction.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return _interpolateValueAction__WEBPACK_IMPORTED_MODULE_7__["InterpolateValueAction"]; }); /***/ }), /***/ "./Actions/interpolateValueAction.ts": /*!*******************************************!*\ !*** ./Actions/interpolateValueAction.ts ***! \*******************************************/ /*! exports provided: InterpolateValueAction */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return InterpolateValueAction; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./action */ "./Actions/action.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /** * This defines an action responsible to change the value of a property * by interpolating between its current value and the newly set one once triggered. * @see https://doc.babylonjs.com/how_to/how_to_use_actions */ var InterpolateValueAction = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InterpolateValueAction, _super); /** * Instantiate the action * @param triggerOptions defines the trigger options * @param target defines the object containing the value to interpolate * @param propertyPath defines the path to the property in the target object * @param value defines the target value at the end of the interpolation * @param duration deines the time it will take for the property to interpolate to the value. * @param condition defines the trigger related conditions * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered * @param onInterpolationDone defines a callback raised once the interpolation animation has been done */ function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) { if (duration === void 0) { duration = 1000; } var _this = _super.call(this, triggerOptions, condition) || this; /** * Defines the time it will take for the property to interpolate to the value. */ _this.duration = 1000; /** * Observable triggered once the interpolation animation has been done. */ _this.onInterpolationDoneObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"](); _this.propertyPath = propertyPath; _this.value = value; _this.duration = duration; _this.stopOtherAnimations = stopOtherAnimations; _this.onInterpolationDone = onInterpolationDone; _this._target = _this._effectiveTarget = target; return _this; } /** @hidden */ InterpolateValueAction.prototype._prepare = function () { this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath); this._property = this._getProperty(this.propertyPath); }; /** * Execute the action starts the value interpolation. */ InterpolateValueAction.prototype.execute = function () { var _this = this; var scene = this._actionManager.getScene(); var keys = [ { frame: 0, value: this._effectiveTarget[this._property] }, { frame: 100, value: this.value } ]; var dataType; if (typeof this.value === "number") { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"].ANIMATIONTYPE_FLOAT; } else if (this.value instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"].ANIMATIONTYPE_COLOR3; } else if (this.value instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"].ANIMATIONTYPE_VECTOR3; } else if (this.value instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"].ANIMATIONTYPE_MATRIX; } else if (this.value instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Quaternion"]) { dataType = _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"].ANIMATIONTYPE_QUATERNION; } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")"); return; } var animation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"]("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, _Animations_animation__WEBPACK_IMPORTED_MODULE_6__["Animation"].ANIMATIONLOOPMODE_CONSTANT); animation.setKeys(keys); if (this.stopOtherAnimations) { scene.stopAnimation(this._effectiveTarget); } var wrapper = function () { _this.onInterpolationDoneObservable.notifyObservers(_this); if (_this.onInterpolationDone) { _this.onInterpolationDone(); } }; scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper); }; /** * Serializes the actions and its related information. * @param parent defines the object to serialize in * @returns the serialized object */ InterpolateValueAction.prototype.serialize = function (parent) { return _super.prototype._serialize.call(this, { name: "InterpolateValueAction", properties: [ _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._GetTargetProperty(this._target), { name: "propertyPath", value: this.propertyPath }, { name: "value", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.value) }, { name: "duration", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.duration) }, { name: "stopOtherAnimations", value: _action__WEBPACK_IMPORTED_MODULE_1__["Action"]._SerializeValueAsString(this.stopOtherAnimations) || false } ] }, parent); }; return InterpolateValueAction; }(_action__WEBPACK_IMPORTED_MODULE_1__["Action"])); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.InterpolateValueAction"] = InterpolateValueAction; /***/ }), /***/ "./Animations/animatable.interface.ts": /*!********************************************!*\ !*** ./Animations/animatable.interface.ts ***! \********************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /***/ }), /***/ "./Animations/animatable.ts": /*!**********************************!*\ !*** ./Animations/animatable.ts ***! \**********************************/ /*! exports provided: Animatable */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return Animatable; }); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony import */ var _runtimeAnimation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./runtimeAnimation */ "./Animations/runtimeAnimation.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/precisionDate */ "./Misc/precisionDate.ts"); /* harmony import */ var _Bones_bone__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Bones/bone */ "./Bones/bone.ts"); /** * Class used to store an actual running animation */ var Animatable = /** @class */ (function () { /** * Creates a new Animatable * @param scene defines the hosting scene * @param target defines the target object * @param fromFrame defines the starting frame number (default is 0) * @param toFrame defines the ending frame number (default is 100) * @param loopAnimation defines if the animation must loop (default is false) * @param speedRatio defines the factor to apply to animation speed (default is 1) * @param onAnimationEnd defines a callback to call when animation ends if it is not looping * @param animations defines a group of animation to add to the new Animatable * @param onAnimationLoop defines a callback to call when animation loops * @param isAdditive defines whether the animation should be evaluated additively */ function Animatable(scene, /** defines the target object */ target, /** defines the starting frame number (default is 0) */ fromFrame, /** defines the ending frame number (default is 100) */ toFrame, /** defines if the animation must loop (default is false) */ loopAnimation, speedRatio, /** defines a callback to call when animation ends if it is not looping */ onAnimationEnd, animations, /** defines a callback to call when animation loops */ onAnimationLoop, /** defines whether the animation should be evaluated additively */ isAdditive) { if (fromFrame === void 0) { fromFrame = 0; } if (toFrame === void 0) { toFrame = 100; } if (loopAnimation === void 0) { loopAnimation = false; } if (speedRatio === void 0) { speedRatio = 1.0; } if (isAdditive === void 0) { isAdditive = false; } this.target = target; this.fromFrame = fromFrame; this.toFrame = toFrame; this.loopAnimation = loopAnimation; this.onAnimationEnd = onAnimationEnd; this.onAnimationLoop = onAnimationLoop; this.isAdditive = isAdditive; this._localDelayOffset = null; this._pausedDelay = null; this._runtimeAnimations = new Array(); this._paused = false; this._speedRatio = 1; this._weight = -1.0; this._syncRoot = null; /** * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation. * This will only apply for non looping animation (default is true) */ this.disposeOnEnd = true; /** * Gets a boolean indicating if the animation has started */ this.animationStarted = false; /** * Observer raised when the animation ends */ this.onAnimationEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observer raised when the animation loops */ this.onAnimationLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); this._scene = scene; if (animations) { this.appendAnimations(target, animations); } this._speedRatio = speedRatio; scene._activeAnimatables.push(this); } Object.defineProperty(Animatable.prototype, "syncRoot", { /** * Gets the root Animatable used to synchronize and normalize animations */ get: function () { return this._syncRoot; }, enumerable: false, configurable: true }); Object.defineProperty(Animatable.prototype, "masterFrame", { /** * Gets the current frame of the first RuntimeAnimation * Used to synchronize Animatables */ get: function () { if (this._runtimeAnimations.length === 0) { return 0; } return this._runtimeAnimations[0].currentFrame; }, enumerable: false, configurable: true }); Object.defineProperty(Animatable.prototype, "weight", { /** * Gets or sets the animatable weight (-1.0 by default meaning not weighted) */ get: function () { return this._weight; }, set: function (value) { if (value === -1) { // -1 is ok and means no weight this._weight = -1; return; } // Else weight must be in [0, 1] range this._weight = Math.min(Math.max(value, 0), 1.0); }, enumerable: false, configurable: true }); Object.defineProperty(Animatable.prototype, "speedRatio", { /** * Gets or sets the speed ratio to apply to the animatable (1.0 by default) */ get: function () { return this._speedRatio; }, set: function (value) { for (var index = 0; index < this._runtimeAnimations.length; index++) { var animation = this._runtimeAnimations[index]; animation._prepareForSpeedRatioChange(value); } this._speedRatio = value; }, enumerable: false, configurable: true }); // Methods /** * Synchronize and normalize current Animatable with a source Animatable * This is useful when using animation weights and when animations are not of the same length * @param root defines the root Animatable to synchronize with * @returns the current Animatable */ Animatable.prototype.syncWith = function (root) { this._syncRoot = root; if (root) { // Make sure this animatable will animate after the root var index = this._scene._activeAnimatables.indexOf(this); if (index > -1) { this._scene._activeAnimatables.splice(index, 1); this._scene._activeAnimatables.push(this); } } return this; }; /** * Gets the list of runtime animations * @returns an array of RuntimeAnimation */ Animatable.prototype.getAnimations = function () { return this._runtimeAnimations; }; /** * Adds more animations to the current animatable * @param target defines the target of the animations * @param animations defines the new animations to add */ Animatable.prototype.appendAnimations = function (target, animations) { var _this = this; for (var index = 0; index < animations.length; index++) { var animation = animations[index]; var newRuntimeAnimation = new _runtimeAnimation__WEBPACK_IMPORTED_MODULE_1__["RuntimeAnimation"](target, animation, this._scene, this); newRuntimeAnimation._onLoop = function () { _this.onAnimationLoopObservable.notifyObservers(_this); if (_this.onAnimationLoop) { _this.onAnimationLoop(); } }; this._runtimeAnimations.push(newRuntimeAnimation); } }; /** * Gets the source animation for a specific property * @param property defines the propertyu to look for * @returns null or the source animation for the given property */ Animatable.prototype.getAnimationByTargetProperty = function (property) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index].animation; } } return null; }; /** * Gets the runtime animation for a specific property * @param property defines the propertyu to look for * @returns null or the runtime animation for the given property */ Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { if (runtimeAnimations[index].animation.targetProperty === property) { return runtimeAnimations[index]; } } return null; }; /** * Resets the animatable to its original state */ Animatable.prototype.reset = function () { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].reset(true); } this._localDelayOffset = null; this._pausedDelay = null; }; /** * Allows the animatable to blend with current running animations * @see https://doc.babylonjs.com/babylon101/animations#animation-blending * @param blendingSpeed defines the blending speed to use */ Animatable.prototype.enableBlending = function (blendingSpeed) { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = true; runtimeAnimations[index].animation.blendingSpeed = blendingSpeed; } }; /** * Disable animation blending * @see https://doc.babylonjs.com/babylon101/animations#animation-blending */ Animatable.prototype.disableBlending = function () { var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].animation.enableBlending = false; } }; /** * Jump directly to a given frame * @param frame defines the frame to jump to */ Animatable.prototype.goToFrame = function (frame) { var runtimeAnimations = this._runtimeAnimations; if (runtimeAnimations[0]) { var fps = runtimeAnimations[0].animation.framePerSecond; var currentFrame = runtimeAnimations[0].currentFrame; var delay = this.speedRatio === 0 ? 0 : ((frame - currentFrame) / fps * 1000) / this.speedRatio; if (this._localDelayOffset === null) { this._localDelayOffset = 0; } this._localDelayOffset -= delay; } for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].goToFrame(frame); } }; /** * Pause the animation */ Animatable.prototype.pause = function () { if (this._paused) { return; } this._paused = true; }; /** * Restart the animation */ Animatable.prototype.restart = function () { this._paused = false; }; Animatable.prototype._raiseOnAnimationEnd = function () { if (this.onAnimationEnd) { this.onAnimationEnd(); } this.onAnimationEndObservable.notifyObservers(this); }; /** * Stop and delete the current animation * @param animationName defines a string used to only stop some of the runtime animations instead of all * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty) */ Animatable.prototype.stop = function (animationName, targetMask) { if (animationName || targetMask) { var idx = this._scene._activeAnimatables.indexOf(this); if (idx > -1) { var runtimeAnimations = this._runtimeAnimations; for (var index = runtimeAnimations.length - 1; index >= 0; index--) { var runtimeAnimation = runtimeAnimations[index]; if (animationName && runtimeAnimation.animation.name != animationName) { continue; } if (targetMask && !targetMask(runtimeAnimation.target)) { continue; } runtimeAnimation.dispose(); runtimeAnimations.splice(index, 1); } if (runtimeAnimations.length == 0) { this._scene._activeAnimatables.splice(idx, 1); this._raiseOnAnimationEnd(); } } } else { var index = this._scene._activeAnimatables.indexOf(this); if (index > -1) { this._scene._activeAnimatables.splice(index, 1); var runtimeAnimations = this._runtimeAnimations; for (var index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].dispose(); } this._raiseOnAnimationEnd(); } } }; /** * Wait asynchronously for the animation to end * @returns a promise which will be fullfilled when the animation ends */ Animatable.prototype.waitAsync = function () { var _this = this; return new Promise(function (resolve, reject) { _this.onAnimationEndObservable.add(function () { resolve(_this); }, undefined, undefined, _this, true); }); }; /** @hidden */ Animatable.prototype._animate = function (delay) { if (this._paused) { this.animationStarted = false; if (this._pausedDelay === null) { this._pausedDelay = delay; } return true; } if (this._localDelayOffset === null) { this._localDelayOffset = delay; this._pausedDelay = null; } else if (this._pausedDelay !== null) { this._localDelayOffset += delay - this._pausedDelay; this._pausedDelay = null; } if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused return true; } // Animating var running = false; var runtimeAnimations = this._runtimeAnimations; var index; for (index = 0; index < runtimeAnimations.length; index++) { var animation = runtimeAnimations[index]; var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight); running = running || isRunning; } this.animationStarted = running; if (!running) { if (this.disposeOnEnd) { // Remove from active animatables index = this._scene._activeAnimatables.indexOf(this); this._scene._activeAnimatables.splice(index, 1); // Dispose all runtime animations for (index = 0; index < runtimeAnimations.length; index++) { runtimeAnimations[index].dispose(); } } this._raiseOnAnimationEnd(); if (this.disposeOnEnd) { this.onAnimationEnd = null; this.onAnimationLoop = null; this.onAnimationLoopObservable.clear(); this.onAnimationEndObservable.clear(); } } return running; }; return Animatable; }()); _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._animate = function () { if (!this.animationsEnabled) { return; } // Getting time var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_5__["PrecisionDate"].Now; if (!this._animationTimeLast) { if (this._pendingData.length > 0) { return; } this._animationTimeLast = now; } this.deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale; this._animationTimeLast = now; var animatables = this._activeAnimatables; if (animatables.length === 0) { return; } this._animationTime += this.deltaTime; var animationTime = this._animationTime; for (var index = 0; index < animatables.length; index++) { var animatable = animatables[index]; if (!animatable._animate(animationTime) && animatable.disposeOnEnd) { index--; // Array was updated } } // Late animation bindings this._processLateAnimationBindings(); }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask, onAnimationLoop, isAdditive) { if (weight === void 0) { weight = 1.0; } if (speedRatio === void 0) { speedRatio = 1.0; } if (isAdditive === void 0) { isAdditive = false; } var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask, onAnimationLoop, isAdditive); returnedAnimatable.weight = weight; return returnedAnimatable; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop, isAdditive) { if (speedRatio === void 0) { speedRatio = 1.0; } if (stopCurrent === void 0) { stopCurrent = true; } if (isAdditive === void 0) { isAdditive = false; } if (from > to && speedRatio > 0) { speedRatio *= -1; } if (stopCurrent) { this.stopAnimation(target, undefined, targetMask); } if (!animatable) { animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, undefined, onAnimationLoop, isAdditive); } var shouldRunTargetAnimations = targetMask ? targetMask(target) : true; // Local animations if (target.animations && shouldRunTargetAnimations) { animatable.appendAnimations(target, target.animations); } // Children animations if (target.getAnimatables) { var animatables = target.getAnimatables(); for (var index = 0; index < animatables.length; index++) { this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop); } } animatable.reset(); return animatable; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginHierarchyAnimation = function (target, directDescendantsOnly, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, onAnimationLoop, isAdditive) { if (speedRatio === void 0) { speedRatio = 1.0; } if (stopCurrent === void 0) { stopCurrent = true; } if (isAdditive === void 0) { isAdditive = false; } var children = target.getDescendants(directDescendantsOnly); var result = []; result.push(this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive)); for (var _i = 0, children_1 = children; _i < children_1.length; _i++) { var child = children_1[_i]; result.push(this.beginAnimation(child, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask, undefined, isAdditive)); } return result; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive) { if (isAdditive === void 0) { isAdditive = false; } if (speedRatio === undefined) { speedRatio = 1.0; } if (from > to && speedRatio > 0) { speedRatio *= -1; } var animatable = new Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations, onAnimationLoop, isAdditive); return animatable; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive) { if (isAdditive === void 0) { isAdditive = false; } var children = target.getDescendants(directDescendantsOnly); var result = []; result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); for (var _i = 0, children_2 = children; _i < children_2.length; _i++) { var child = children_2[_i]; result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd, onAnimationLoop, isAdditive)); } return result; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.getAnimatableByTarget = function (target) { for (var index = 0; index < this._activeAnimatables.length; index++) { if (this._activeAnimatables[index].target === target) { return this._activeAnimatables[index]; } } return null; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.getAllAnimatablesByTarget = function (target) { var result = []; for (var index = 0; index < this._activeAnimatables.length; index++) { if (this._activeAnimatables[index].target === target) { result.push(this._activeAnimatables[index]); } } return result; }; /** * Will stop the animation of the given target * @param target - the target * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty) * @param targetMask - a function that determines if the animation should be stopped based on its target (all animations will be stopped if both this and animationName are empty) */ _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.stopAnimation = function (target, animationName, targetMask) { var animatables = this.getAllAnimatablesByTarget(target); for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) { var animatable = animatables_1[_i]; animatable.stop(animationName, targetMask); } }; /** * Stops and removes all animations that have been applied to the scene */ _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype.stopAllAnimations = function () { if (this._activeAnimatables) { for (var i = 0; i < this._activeAnimatables.length; i++) { this._activeAnimatables[i].stop(); } this._activeAnimatables = []; } for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) { var group = _a[_i]; group.stop(); } }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) { var target = runtimeAnimation.target; this._registeredForLateAnimationBindings.pushNoDuplicate(target); if (!target._lateAnimationHolders) { target._lateAnimationHolders = {}; } if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) { target._lateAnimationHolders[runtimeAnimation.targetPath] = { totalWeight: 0, totalAdditiveWeight: 0, animations: [], additiveAnimations: [], originalValue: originalValue }; } if (runtimeAnimation.isAdditive) { target._lateAnimationHolders[runtimeAnimation.targetPath].additiveAnimations.push(runtimeAnimation); target._lateAnimationHolders[runtimeAnimation.targetPath].totalAdditiveWeight += runtimeAnimation.weight; } else { target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation); target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight; } }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindingsForMatrices = function (holder) { if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { return holder.originalValue; } var normalizer = 1.0; var finalPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Vector3[0]; var finalScaling = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Vector3[1]; var finalQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Quaternion[0]; var startIndex = 0; var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; var scale = 1; var skipOverride = false; if (holder.totalWeight < 1.0) { // We need to mix the original value in scale = 1.0 - holder.totalWeight; originalValue.decompose(finalScaling, finalQuaternion, finalPosition); } else { startIndex = 1; // We need to normalize the weights normalizer = holder.totalWeight; scale = originalAnimation.weight / normalizer; if (scale == 1) { if (holder.totalAdditiveWeight) { skipOverride = true; } else { return originalAnimation.currentValue; } } originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition); } // Add up the override animations if (!skipOverride) { finalScaling.scaleInPlace(scale); finalPosition.scaleInPlace(scale); finalQuaternion.scaleInPlace(scale); for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { var runtimeAnimation = holder.animations[animIndex]; if (runtimeAnimation.weight === 0) { continue; } var scale = runtimeAnimation.weight / normalizer; var currentPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Vector3[2]; var currentScaling = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Vector3[3]; var currentQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Quaternion[1]; runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); currentScaling.scaleAndAddToRef(scale, finalScaling); currentQuaternion.scaleAndAddToRef(scale, finalQuaternion); currentPosition.scaleAndAddToRef(scale, finalPosition); } } // Add up the additive animations for (var animIndex_1 = 0; animIndex_1 < holder.additiveAnimations.length; animIndex_1++) { var runtimeAnimation = holder.additiveAnimations[animIndex_1]; if (runtimeAnimation.weight === 0) { continue; } var currentPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Vector3[2]; var currentScaling = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Vector3[3]; var currentQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Quaternion[1]; runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition); currentScaling.multiplyToRef(finalScaling, currentScaling); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].LerpToRef(finalScaling, currentScaling, runtimeAnimation.weight, finalScaling); finalQuaternion.multiplyToRef(currentQuaternion, currentQuaternion); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(finalQuaternion, currentQuaternion, runtimeAnimation.weight, finalQuaternion); currentPosition.scaleAndAddToRef(runtimeAnimation.weight, finalPosition); } var workValue = originalAnimation ? originalAnimation._animationState.workValue : _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Matrix[0].clone(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].ComposeToRef(finalScaling, finalQuaternion, finalPosition, workValue); return workValue; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) { if (holder.totalWeight === 0 && holder.totalAdditiveWeight === 0) { return refQuaternion; } var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; var cumulativeQuaternion = refQuaternion; if (holder.totalWeight === 0 && holder.totalAdditiveWeight > 0) { cumulativeQuaternion.copyFrom(originalValue); } else if (holder.animations.length === 1) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), cumulativeQuaternion); if (holder.totalAdditiveWeight === 0) { return cumulativeQuaternion; } } else if (holder.animations.length > 1) { // Add up the override animations var normalizer = 1.0; var quaternions = void 0; var weights = void 0; if (holder.totalWeight < 1.0) { var scale = 1.0 - holder.totalWeight; quaternions = []; weights = []; quaternions.push(originalValue); weights.push(scale); } else { if (holder.animations.length === 2) { // Slerp as soon as we can _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion); if (holder.totalAdditiveWeight === 0) { return refQuaternion; } } quaternions = []; weights = []; normalizer = holder.totalWeight; } for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) { var runtimeAnimation = holder.animations[animIndex]; quaternions.push(runtimeAnimation.currentValue); weights.push(runtimeAnimation.weight / normalizer); } // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions var cumulativeAmount = 0; for (var index = 0; index < quaternions.length;) { if (!index) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion); cumulativeQuaternion = refQuaternion; cumulativeAmount = weights[index] + weights[index + 1]; index += 2; continue; } cumulativeAmount += weights[index]; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion); index++; } } // Add up the additive animations for (var animIndex_2 = 0; animIndex_2 < holder.additiveAnimations.length; animIndex_2++) { var runtimeAnimation = holder.additiveAnimations[animIndex_2]; if (runtimeAnimation.weight === 0) { continue; } cumulativeQuaternion.multiplyToRef(runtimeAnimation.currentValue, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Quaternion[0]); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].SlerpToRef(cumulativeQuaternion, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Quaternion[0], runtimeAnimation.weight, cumulativeQuaternion); } return cumulativeQuaternion; }; _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype._processLateAnimationBindings = function () { if (!this._registeredForLateAnimationBindings.length) { return; } for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) { var target = this._registeredForLateAnimationBindings.data[index]; for (var path in target._lateAnimationHolders) { var holder = target._lateAnimationHolders[path]; var originalAnimation = holder.animations[0]; var originalValue = holder.originalValue; var matrixDecomposeMode = _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix var finalValue = target[path]; if (matrixDecomposeMode) { finalValue = this._processLateAnimationBindingsForMatrices(holder); } else { var quaternionMode = originalValue.w !== undefined; if (quaternionMode) { finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity()); } else { var startIndex = 0; var normalizer = 1.0; if (holder.totalWeight < 1.0) { // We need to mix the original value in if (originalAnimation && originalValue.scale) { finalValue = originalValue.scale(1.0 - holder.totalWeight); } else if (originalAnimation) { finalValue = originalValue * (1.0 - holder.totalWeight); } else if (originalValue.clone) { finalValue = originalValue.clone(); } else { finalValue = originalValue; } } else if (originalAnimation) { // We need to normalize the weights normalizer = holder.totalWeight; var scale_1 = originalAnimation.weight / normalizer; if (scale_1 !== 1) { if (originalAnimation.currentValue.scale) { finalValue = originalAnimation.currentValue.scale(scale_1); } else { finalValue = originalAnimation.currentValue * scale_1; } } else { finalValue = originalAnimation.currentValue; } startIndex = 1; } // Add up the override animations for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) { var runtimeAnimation = holder.animations[animIndex]; var scale = runtimeAnimation.weight / normalizer; if (!scale) { continue; } else if (runtimeAnimation.currentValue.scaleAndAddToRef) { runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); } else { finalValue += runtimeAnimation.currentValue * scale; } } // Add up the additive animations for (var animIndex_3 = 0; animIndex_3 < holder.additiveAnimations.length; animIndex_3++) { var runtimeAnimation = holder.additiveAnimations[animIndex_3]; var scale = runtimeAnimation.weight; if (!scale) { continue; } else if (runtimeAnimation.currentValue.scaleAndAddToRef) { runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue); } else { finalValue += runtimeAnimation.currentValue * scale; } } } } target[path] = finalValue; } target._lateAnimationHolders = {}; } this._registeredForLateAnimationBindings.reset(); }; _Bones_bone__WEBPACK_IMPORTED_MODULE_6__["Bone"].prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) { if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; } // all animation may be coming from a library skeleton, so may need to create animation if (this.animations.length === 0) { this.animations.push(new _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"](this.name, "_matrix", source.animations[0].framePerSecond, _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_MATRIX, 0)); this.animations[0].setKeys([]); } // get animation info / verify there is such a range from the source bone var sourceRange = source.animations[0].getRange(rangeName); if (!sourceRange) { return false; } var from = sourceRange.from; var to = sourceRange.to; var sourceKeys = source.animations[0].getKeys(); // rescaling prep var sourceBoneLength = source.length; var sourceParent = source.getParent(); var parent = this.getParent(); var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length; var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1; var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1); var destKeys = this.animations[0].getKeys(); // loop vars declaration var orig; var origTranslation; var mat; for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) { orig = sourceKeys[key]; if (orig.frame >= from && orig.frame <= to) { if (rescaleAsRequired) { mat = orig.value.clone(); // scale based on parent ratio, when bone has parent if (parentScalingReqd) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.scaleInPlace(parentRatio)); // scale based on skeleton dimension ratio when root bone, and value is passed } else if (dimensionsScalingReqd && skelDimensionsRatio) { origTranslation = mat.getTranslation(); mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio)); // use original when root bone, and no data for skelDimensionsRatio } else { mat = orig.value; } } else { mat = orig.value; } destKeys.push({ frame: orig.frame + frameOffset, value: mat }); } } this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset); return true; }; /***/ }), /***/ "./Animations/animation.ts": /*!*********************************!*\ !*** ./Animations/animation.ts ***! \*********************************/ /*! exports provided: _IAnimationState, Animation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_IAnimationState", function() { return _IAnimationState; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return Animation; }); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts"); /* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts"); /* harmony import */ var _animationKey__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./animationKey */ "./Animations/animationKey.ts"); /* harmony import */ var _animationRange__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./animationRange */ "./Animations/animationRange.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Maths_math_size__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Maths/math.size */ "./Maths/math.size.ts"); /* harmony import */ var _Misc_webRequest__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/webRequest */ "./Misc/webRequest.ts"); /** * @hidden */ var _IAnimationState = /** @class */ (function () { function _IAnimationState() { } return _IAnimationState; }()); /** * Class used to store any kind of animation */ var Animation = /** @class */ (function () { /** * Initializes the animation * @param name Name of the animation * @param targetProperty Property to animate * @param framePerSecond The frames per second of the animation * @param dataType The data type of the animation * @param loopMode The loop mode of the animation * @param enableBlending Specifies if blending should be enabled */ function Animation( /**Name of the animation */ name, /**Property to animate */ targetProperty, /**The frames per second of the animation */ framePerSecond, /**The data type of the animation */ dataType, /**The loop mode of the animation */ loopMode, /**Specifies if blending should be enabled */ enableBlending) { this.name = name; this.targetProperty = targetProperty; this.framePerSecond = framePerSecond; this.dataType = dataType; this.loopMode = loopMode; this.enableBlending = enableBlending; /** * @hidden Internal use only */ this._runtimeAnimations = new Array(); /** * The set of event that will be linked to this animation */ this._events = new Array(); /** * Stores the blending speed of the animation */ this.blendingSpeed = 0.01; /** * Stores the animation ranges for the animation */ this._ranges = {}; this.targetPropertyPath = targetProperty.split("."); this.dataType = dataType; this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode; } /** * @hidden Internal use */ Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) { var dataType = undefined; if (!isNaN(parseFloat(from)) && isFinite(from)) { dataType = Animation.ANIMATIONTYPE_FLOAT; } else if (from instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]) { dataType = Animation.ANIMATIONTYPE_QUATERNION; } else if (from instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]) { dataType = Animation.ANIMATIONTYPE_VECTOR3; } else if (from instanceof _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"]) { dataType = Animation.ANIMATIONTYPE_VECTOR2; } else if (from instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color3"]) { dataType = Animation.ANIMATIONTYPE_COLOR3; } else if (from instanceof _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color4"]) { dataType = Animation.ANIMATIONTYPE_COLOR4; } else if (from instanceof _Maths_math_size__WEBPACK_IMPORTED_MODULE_8__["Size"]) { dataType = Animation.ANIMATIONTYPE_SIZE; } if (dataType == undefined) { return null; } var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode); var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }]; animation.setKeys(keys); if (easingFunction !== undefined) { animation.setEasingFunction(easingFunction); } return animation; }; /** * Sets up an animation * @param property The property to animate * @param animationType The animation type to apply * @param framePerSecond The frames per second of the animation * @param easingFunction The easing function used in the animation * @returns The created animation */ Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) { var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT); animation.setEasingFunction(easingFunction); return animation; }; /** * Create and start an animation on a node * @param name defines the name of the global animation that will be run on all nodes * @param node defines the root node where the animation will take place * @param targetProperty defines property to animate * @param framePerSecond defines the number of frame per second yo use * @param totalFrame defines the number of frames in total * @param from defines the initial value * @param to defines the final value * @param loopMode defines which loop mode you want to use (off by default) * @param easingFunction defines the easing function to use (linear by default) * @param onAnimationEnd defines the callback to call when animation end * @returns the animatable created for this animation */ Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); }; /** * Create and start an animation on a node and its descendants * @param name defines the name of the global animation that will be run on all nodes * @param node defines the root node where the animation will take place * @param directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used * @param targetProperty defines property to animate * @param framePerSecond defines the number of frame per second to use * @param totalFrame defines the number of frames in total * @param from defines the initial value * @param to defines the final value * @param loopMode defines which loop mode you want to use (off by default) * @param easingFunction defines the easing function to use (linear by default) * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node) * @returns the list of animatables created for all nodes * @example https://www.babylonjs-playground.com/#MH0VLI */ Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } var scene = node.getScene(); return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); }; /** * Creates a new animation, merges it with the existing animations and starts it * @param name Name of the animation * @param node Node which contains the scene that begins the animations * @param targetProperty Specifies which property to animate * @param framePerSecond The frames per second of the animation * @param totalFrame The total number of frames * @param from The frame at the beginning of the animation * @param to The frame at the end of the animation * @param loopMode Specifies the loop mode of the animation * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations * @param onAnimationEnd Callback to run once the animation is complete * @returns Nullable animation */ Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) { var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction); if (!animation) { return null; } node.animations.push(animation); return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd); }; /** * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame. * @param sourceAnimation defines the Animation containing keyframes to convert * @param referenceFrame defines the frame that keyframes in the range will be relative to * @param range defines the name of the AnimationRange belonging to the Animation to convert * @param cloneOriginal defines whether or not to clone the animation and convert the clone or convert the original animation (default is false) * @param clonedName defines the name of the resulting cloned Animation if cloneOriginal is true * @returns a new Animation if cloneOriginal is true or the original Animation if cloneOriginal is false */ Animation.MakeAnimationAdditive = function (sourceAnimation, referenceFrame, range, cloneOriginal, clonedName) { if (referenceFrame === void 0) { referenceFrame = 0; } if (cloneOriginal === void 0) { cloneOriginal = false; } var animation = sourceAnimation; if (cloneOriginal) { animation = sourceAnimation.clone(); animation.name = clonedName || animation.name; } if (!animation._keys.length) { return animation; } referenceFrame = referenceFrame >= 0 ? referenceFrame : 0; var startIndex = 0; var firstKey = animation._keys[0]; var endIndex = animation._keys.length - 1; var lastKey = animation._keys[endIndex]; var valueStore = { referenceValue: firstKey.value, referencePosition: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Vector3[0], referenceQuaternion: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Quaternion[0], referenceScaling: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Vector3[1], keyPosition: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Vector3[2], keyQuaternion: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Quaternion[1], keyScaling: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Vector3[3] }; var referenceFound = false; var from = firstKey.frame; var to = lastKey.frame; if (range) { var rangeValue = animation.getRange(range); if (rangeValue) { from = rangeValue.from; to = rangeValue.to; } } var fromKeyFound = firstKey.frame === from; var toKeyFound = lastKey.frame === to; // There's only one key, so use it if (animation._keys.length === 1) { var value = animation._getKeyValue(animation._keys[0]); valueStore.referenceValue = value.clone ? value.clone() : value; referenceFound = true; } // Reference frame is before the first frame, so just use the first frame else if (referenceFrame <= firstKey.frame) { var value = animation._getKeyValue(firstKey.value); valueStore.referenceValue = value.clone ? value.clone() : value; referenceFound = true; } // Reference frame is after the last frame, so just use the last frame else if (referenceFrame >= lastKey.frame) { var value = animation._getKeyValue(lastKey.value); valueStore.referenceValue = value.clone ? value.clone() : value; referenceFound = true; } // Find key bookends, create them if they don't exist var index = 0; while (!referenceFound || !fromKeyFound || !toKeyFound && index < animation._keys.length - 1) { var currentKey = animation._keys[index]; var nextKey = animation._keys[index + 1]; // If reference frame wasn't found yet, check if we can interpolate to it if (!referenceFound && referenceFrame >= currentKey.frame && referenceFrame <= nextKey.frame) { var value = void 0; if (referenceFrame === currentKey.frame) { value = animation._getKeyValue(currentKey.value); } else if (referenceFrame === nextKey.frame) { value = animation._getKeyValue(nextKey.value); } else { var animationState = { key: index, repeatCount: 0, loopMode: this.ANIMATIONLOOPMODE_CONSTANT }; value = animation._interpolate(referenceFrame, animationState); } valueStore.referenceValue = value.clone ? value.clone() : value; referenceFound = true; } // If from key wasn't found yet, check if we can interpolate to it if (!fromKeyFound && from >= currentKey.frame && from <= nextKey.frame) { if (from === currentKey.frame) { startIndex = index; } else if (from === nextKey.frame) { startIndex = index + 1; } else { var animationState = { key: index, repeatCount: 0, loopMode: this.ANIMATIONLOOPMODE_CONSTANT }; var value = animation._interpolate(from, animationState); var key = { frame: from, value: value.clone ? value.clone() : value }; animation._keys.splice(index + 1, 0, key); startIndex = index + 1; } fromKeyFound = true; } // If to key wasn't found yet, check if we can interpolate to it if (!toKeyFound && to >= currentKey.frame && to <= nextKey.frame) { if (to === currentKey.frame) { endIndex = index; } else if (to === nextKey.frame) { endIndex = index + 1; } else { var animationState = { key: index, repeatCount: 0, loopMode: this.ANIMATIONLOOPMODE_CONSTANT }; var value = animation._interpolate(to, animationState); var key = { frame: to, value: value.clone ? value.clone() : value }; animation._keys.splice(index + 1, 0, key); endIndex = index + 1; } toKeyFound = true; } index++; } // Conjugate the quaternion if (animation.dataType === Animation.ANIMATIONTYPE_QUATERNION) { valueStore.referenceValue.normalize().conjugateInPlace(); } // Decompose matrix and conjugate the quaternion else if (animation.dataType === Animation.ANIMATIONTYPE_MATRIX) { valueStore.referenceValue.decompose(valueStore.referenceScaling, valueStore.referenceQuaternion, valueStore.referencePosition); valueStore.referenceQuaternion.normalize().conjugateInPlace(); } // Subtract the reference value from all of the key values for (var index = startIndex; index <= endIndex; index++) { var key = animation._keys[index]; // If this key was duplicated to create a frame 0 key, skip it because its value has already been updated if (index && animation.dataType !== Animation.ANIMATIONTYPE_FLOAT && key.value === firstKey.value) { continue; } switch (animation.dataType) { case Animation.ANIMATIONTYPE_MATRIX: key.value.decompose(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition); valueStore.keyPosition.subtractInPlace(valueStore.referencePosition); valueStore.keyScaling.divideInPlace(valueStore.referenceScaling); valueStore.referenceQuaternion.multiplyToRef(valueStore.keyQuaternion, valueStore.keyQuaternion); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].ComposeToRef(valueStore.keyScaling, valueStore.keyQuaternion, valueStore.keyPosition, key.value); break; case Animation.ANIMATIONTYPE_QUATERNION: valueStore.referenceValue.multiplyToRef(key.value, key.value); break; case Animation.ANIMATIONTYPE_VECTOR2: case Animation.ANIMATIONTYPE_VECTOR3: case Animation.ANIMATIONTYPE_COLOR3: case Animation.ANIMATIONTYPE_COLOR4: key.value.subtractToRef(valueStore.referenceValue, key.value); break; case Animation.ANIMATIONTYPE_SIZE: key.value.width -= valueStore.referenceValue.width; key.value.height -= valueStore.referenceValue.height; break; default: key.value -= valueStore.referenceValue; } } return animation; }; /** * Transition property of an host to the target Value * @param property The property to transition * @param targetValue The target Value of the property * @param host The object where the property to animate belongs * @param scene Scene used to run the animation * @param frameRate Framerate (in frame/s) to use * @param transition The transition type we want to use * @param duration The duration of the animation, in milliseconds * @param onAnimationEnd Callback trigger at the end of the animation * @returns Nullable animation */ Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) { if (onAnimationEnd === void 0) { onAnimationEnd = null; } if (duration <= 0) { host[property] = targetValue; if (onAnimationEnd) { onAnimationEnd(); } return null; } var endFrame = frameRate * (duration / 1000); transition.setKeys([{ frame: 0, value: host[property].clone ? host[property].clone() : host[property] }, { frame: endFrame, value: targetValue }]); if (!host.animations) { host.animations = []; } host.animations.push(transition); var animation = scene.beginAnimation(host, 0, endFrame, false); animation.onAnimationEnd = onAnimationEnd; return animation; }; Object.defineProperty(Animation.prototype, "runtimeAnimations", { /** * Return the array of runtime animations currently using this animation */ get: function () { return this._runtimeAnimations; }, enumerable: false, configurable: true }); Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", { /** * Specifies if any of the runtime animations are currently running */ get: function () { for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) { var runtimeAnimation = _a[_i]; if (!runtimeAnimation.isStopped) { return true; } } return false; }, enumerable: false, configurable: true }); // Methods /** * Converts the animation to a string * @param fullDetails support for multiple levels of logging within scene loading * @returns String form of the animation */ Animation.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name + ", property: " + this.targetProperty; ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType]; ret += ", nKeys: " + (this._keys ? this._keys.length : "none"); ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); if (fullDetails) { ret += ", Ranges: {"; var first = true; for (var name in this._ranges) { if (first) { ret += ", "; first = false; } ret += name; } ret += "}"; } return ret; }; /** * Add an event to this animation * @param event Event to add */ Animation.prototype.addEvent = function (event) { this._events.push(event); this._events.sort(function (a, b) { return a.frame - b.frame; }); }; /** * Remove all events found at the given frame * @param frame The frame to remove events from */ Animation.prototype.removeEvents = function (frame) { for (var index = 0; index < this._events.length; index++) { if (this._events[index].frame === frame) { this._events.splice(index, 1); index--; } } }; /** * Retrieves all the events from the animation * @returns Events from the animation */ Animation.prototype.getEvents = function () { return this._events; }; /** * Creates an animation range * @param name Name of the animation range * @param from Starting frame of the animation range * @param to Ending frame of the animation */ Animation.prototype.createRange = function (name, from, to) { // check name not already in use; could happen for bones after serialized if (!this._ranges[name]) { this._ranges[name] = new _animationRange__WEBPACK_IMPORTED_MODULE_6__["AnimationRange"](name, from, to); } }; /** * Deletes an animation range by name * @param name Name of the animation range to delete * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false) */ Animation.prototype.deleteRange = function (name, deleteFrames) { if (deleteFrames === void 0) { deleteFrames = true; } var range = this._ranges[name]; if (!range) { return; } if (deleteFrames) { var from = range.from; var to = range.to; // this loop MUST go high to low for multiple splices to work for (var key = this._keys.length - 1; key >= 0; key--) { if (this._keys[key].frame >= from && this._keys[key].frame <= to) { this._keys.splice(key, 1); } } } this._ranges[name] = null; // said much faster than 'delete this._range[name]' }; /** * Gets the animation range by name, or null if not defined * @param name Name of the animation range * @returns Nullable animation range */ Animation.prototype.getRange = function (name) { return this._ranges[name]; }; /** * Gets the key frames from the animation * @returns The key frames of the animation */ Animation.prototype.getKeys = function () { return this._keys; }; /** * Gets the highest frame rate of the animation * @returns Highest frame rate of the animation */ Animation.prototype.getHighestFrame = function () { var ret = 0; for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) { if (ret < this._keys[key].frame) { ret = this._keys[key].frame; } } return ret; }; /** * Gets the easing function of the animation * @returns Easing function of the animation */ Animation.prototype.getEasingFunction = function () { return this._easingFunction; }; /** * Sets the easing function of the animation * @param easingFunction A custom mathematical formula for animation */ Animation.prototype.setEasingFunction = function (easingFunction) { this._easingFunction = easingFunction; }; /** * Interpolates a scalar linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated scalar value */ Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__["Scalar"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a scalar cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated scalar value */ Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__["Scalar"].Hermite(startValue, outTangent, endValue, inTangent, gradient); }; /** * Interpolates a quaternion using a spherical linear interpolation * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated quaternion value */ Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Slerp(startValue, endValue, gradient); }; /** * Interpolates a quaternion cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation curve * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated quaternion value */ Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize(); }; /** * Interpolates a Vector3 linearl * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated scalar value */ Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Vector3 cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns InterpolatedVector3 value */ Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Hermite(startValue, outTangent, endValue, inTangent, gradient); }; /** * Interpolates a Vector2 linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Vector2 value */ Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Vector2 cubically * @param startValue Start value of the animation curve * @param outTangent End tangent of the animation * @param endValue End value of the animation curve * @param inTangent Start tangent of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Vector2 value */ Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Hermite(startValue, outTangent, endValue, inTangent, gradient); }; /** * Interpolates a size linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Size value */ Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_size__WEBPACK_IMPORTED_MODULE_8__["Size"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Color3 linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Color3 value */ Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color3"].Lerp(startValue, endValue, gradient); }; /** * Interpolates a Color4 linearly * @param startValue Start value of the animation curve * @param endValue End value of the animation curve * @param gradient Scalar amount to interpolate * @returns Interpolated Color3 value */ Animation.prototype.color4InterpolateFunction = function (startValue, endValue, gradient) { return _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color4"].Lerp(startValue, endValue, gradient); }; /** * @hidden Internal use only */ Animation.prototype._getKeyValue = function (value) { if (typeof value === "function") { return value(); } return value; }; /** * @hidden Internal use only */ Animation.prototype._interpolate = function (currentFrame, state) { if (state.loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && state.repeatCount > 0) { return state.highLimitValue.clone ? state.highLimitValue.clone() : state.highLimitValue; } var keys = this._keys; if (keys.length === 1) { return this._getKeyValue(keys[0].value); } var startKeyIndex = state.key; if (keys[startKeyIndex].frame >= currentFrame) { while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) { startKeyIndex--; } } for (var key = startKeyIndex; key < keys.length; key++) { var endKey = keys[key + 1]; if (endKey.frame >= currentFrame) { state.key = key; var startKey = keys[key]; var startValue = this._getKeyValue(startKey.value); if (startKey.interpolation === _animationKey__WEBPACK_IMPORTED_MODULE_5__["AnimationKeyInterpolation"].STEP) { return startValue; } var endValue = this._getKeyValue(endKey.value); var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined; var frameDelta = endKey.frame - startKey.frame; // gradient : percent of currentFrame between the frame inf and the frame sup var gradient = (currentFrame - startKey.frame) / frameDelta; // check for easingFunction and correction of gradient var easingFunction = this.getEasingFunction(); if (easingFunction != null) { gradient = easingFunction.ease(gradient); } switch (this.dataType) { // Float case Animation.ANIMATIONTYPE_FLOAT: var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient); switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return floatValue; case Animation.ANIMATIONLOOPMODE_RELATIVE: return state.offsetValue * state.repeatCount + floatValue; } break; // Quaternion case Animation.ANIMATIONTYPE_QUATERNION: var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient); switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return quatValue; case Animation.ANIMATIONLOOPMODE_RELATIVE: return quatValue.addInPlace(state.offsetValue.scale(state.repeatCount)); } return quatValue; // Vector3 case Animation.ANIMATIONTYPE_VECTOR3: var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient); switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return vec3Value; case Animation.ANIMATIONLOOPMODE_RELATIVE: return vec3Value.add(state.offsetValue.scale(state.repeatCount)); } // Vector2 case Animation.ANIMATIONTYPE_VECTOR2: var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient); switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return vec2Value; case Animation.ANIMATIONLOOPMODE_RELATIVE: return vec2Value.add(state.offsetValue.scale(state.repeatCount)); } // Size case Animation.ANIMATIONTYPE_SIZE: switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.sizeInterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.sizeInterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount)); } // Color3 case Animation.ANIMATIONTYPE_COLOR3: switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.color3InterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.color3InterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount)); } // Color4 case Animation.ANIMATIONTYPE_COLOR4: switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: return this.color4InterpolateFunction(startValue, endValue, gradient); case Animation.ANIMATIONLOOPMODE_RELATIVE: return this.color4InterpolateFunction(startValue, endValue, gradient).add(state.offsetValue.scale(state.repeatCount)); } // Matrix case Animation.ANIMATIONTYPE_MATRIX: switch (state.loopMode) { case Animation.ANIMATIONLOOPMODE_CYCLE: case Animation.ANIMATIONLOOPMODE_CONSTANT: if (Animation.AllowMatricesInterpolation) { return this.matrixInterpolateFunction(startValue, endValue, gradient, state.workValue); } case Animation.ANIMATIONLOOPMODE_RELATIVE: return startValue; } default: break; } break; } } return this._getKeyValue(keys[keys.length - 1].value); }; /** * Defines the function to use to interpolate matrices * @param startValue defines the start matrix * @param endValue defines the end matrix * @param gradient defines the gradient between both matrices * @param result defines an optional target matrix where to store the interpolation * @returns the interpolated matrix */ Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) { if (Animation.AllowMatrixDecomposeForInterpolation) { if (result) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerpToRef(startValue, endValue, gradient, result); return result; } return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerp(startValue, endValue, gradient); } if (result) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LerpToRef(startValue, endValue, gradient, result); return result; } return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Lerp(startValue, endValue, gradient); }; /** * Makes a copy of the animation * @returns Cloned animation */ Animation.prototype.clone = function () { var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode); clone.enableBlending = this.enableBlending; clone.blendingSpeed = this.blendingSpeed; if (this._keys) { clone.setKeys(this._keys); } if (this._ranges) { clone._ranges = {}; for (var name in this._ranges) { var range = this._ranges[name]; if (!range) { continue; } clone._ranges[name] = range.clone(); } } return clone; }; /** * Sets the key frames of the animation * @param values The animation key frames to set */ Animation.prototype.setKeys = function (values) { this._keys = values.slice(0); }; /** * Serializes the animation to an object * @returns Serialized object */ Animation.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.property = this.targetProperty; serializationObject.framePerSecond = this.framePerSecond; serializationObject.dataType = this.dataType; serializationObject.loopBehavior = this.loopMode; serializationObject.enableBlending = this.enableBlending; serializationObject.blendingSpeed = this.blendingSpeed; var dataType = this.dataType; serializationObject.keys = []; var keys = this.getKeys(); for (var index = 0; index < keys.length; index++) { var animationKey = keys[index]; var key = {}; key.frame = animationKey.frame; switch (dataType) { case Animation.ANIMATIONTYPE_FLOAT: key.values = [animationKey.value]; if (animationKey.inTangent !== undefined) { key.values.push(animationKey.inTangent); } if (animationKey.outTangent !== undefined) { if (animationKey.inTangent === undefined) { key.values.push(undefined); } key.values.push(animationKey.outTangent); } break; case Animation.ANIMATIONTYPE_QUATERNION: case Animation.ANIMATIONTYPE_MATRIX: case Animation.ANIMATIONTYPE_VECTOR3: case Animation.ANIMATIONTYPE_COLOR3: case Animation.ANIMATIONTYPE_COLOR4: key.values = animationKey.value.asArray(); if (animationKey.inTangent != undefined) { key.values.push(animationKey.inTangent.asArray()); } if (animationKey.outTangent != undefined) { if (animationKey.inTangent === undefined) { key.values.push(undefined); } key.values.push(animationKey.outTangent.asArray()); } break; } serializationObject.keys.push(key); } serializationObject.ranges = []; for (var name in this._ranges) { var source = this._ranges[name]; if (!source) { continue; } var range = {}; range.name = name; range.from = source.from; range.to = source.to; serializationObject.ranges.push(range); } return serializationObject; }; /** @hidden */ Animation._UniversalLerp = function (left, right, amount) { var constructor = left.constructor; if (constructor.Lerp) { // Lerp supported return constructor.Lerp(left, right, amount); } else if (constructor.Slerp) { // Slerp supported return constructor.Slerp(left, right, amount); } else if (left.toFixed) { // Number return left * (1.0 - amount) + amount * right; } else { // Blending not supported return right; } }; /** * Parses an animation object and creates an animation * @param parsedAnimation Parsed animation object * @returns Animation object */ Animation.Parse = function (parsedAnimation) { var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior); var dataType = parsedAnimation.dataType; var keys = []; var data; var index; if (parsedAnimation.enableBlending) { animation.enableBlending = parsedAnimation.enableBlending; } if (parsedAnimation.blendingSpeed) { animation.blendingSpeed = parsedAnimation.blendingSpeed; } for (index = 0; index < parsedAnimation.keys.length; index++) { var key = parsedAnimation.keys[index]; var inTangent; var outTangent; switch (dataType) { case Animation.ANIMATIONTYPE_FLOAT: data = key.values[0]; if (key.values.length >= 1) { inTangent = key.values[1]; } if (key.values.length >= 2) { outTangent = key.values[2]; } break; case Animation.ANIMATIONTYPE_QUATERNION: data = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values); if (key.values.length >= 8) { var _inTangent = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values.slice(4, 8)); if (!_inTangent.equals(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Zero())) { inTangent = _inTangent; } } if (key.values.length >= 12) { var _outTangent = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(key.values.slice(8, 12)); if (!_outTangent.equals(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Zero())) { outTangent = _outTangent; } } break; case Animation.ANIMATIONTYPE_MATRIX: data = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromArray(key.values); break; case Animation.ANIMATIONTYPE_COLOR3: data = _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color3"].FromArray(key.values); break; case Animation.ANIMATIONTYPE_COLOR4: data = _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color4"].FromArray(key.values); break; case Animation.ANIMATIONTYPE_VECTOR3: default: data = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(key.values); break; } var keyData = {}; keyData.frame = key.frame; keyData.value = data; if (inTangent != undefined) { keyData.inTangent = inTangent; } if (outTangent != undefined) { keyData.outTangent = outTangent; } keys.push(keyData); } animation.setKeys(keys); if (parsedAnimation.ranges) { for (index = 0; index < parsedAnimation.ranges.length; index++) { data = parsedAnimation.ranges[index]; animation.createRange(data.name, data.from, data.to); } } return animation; }; /** * Appends the serialized animations from the source animations * @param source Source containing the animations * @param destination Target to store the animations */ Animation.AppendSerializedAnimations = function (source, destination) { _Misc_decorators__WEBPACK_IMPORTED_MODULE_3__["SerializationHelper"].AppendSerializedAnimations(source, destination); }; /** * Creates a new animation or an array of animations from a snippet saved in a remote file * @param name defines the name of the animation to create (can be null or empty to use the one from the json data) * @param url defines the url to load from * @returns a promise that will resolve to the new animation or an array of animations */ Animation.ParseFromFileAsync = function (name, url) { var _this = this; return new Promise(function (resolve, reject) { var request = new _Misc_webRequest__WEBPACK_IMPORTED_MODULE_9__["WebRequest"](); request.addEventListener("readystatechange", function () { if (request.readyState == 4) { if (request.status == 200) { var serializationObject = JSON.parse(request.responseText); if (serializationObject.length) { var output = new Array(); for (var _i = 0, serializationObject_1 = serializationObject; _i < serializationObject_1.length; _i++) { var serializedAnimation = serializationObject_1[_i]; output.push(_this.Parse(serializedAnimation)); } resolve(output); } else { var output = _this.Parse(serializationObject); if (name) { output.name = name; } resolve(output); } } else { reject("Unable to load the animation"); } } }); request.open("GET", url); request.send(); }); }; /** * Creates an animation or an array of animations from a snippet saved by the Inspector * @param snippetId defines the snippet to load * @returns a promise that will resolve to the new animation or a new array of animations */ Animation.CreateFromSnippetAsync = function (snippetId) { var _this = this; return new Promise(function (resolve, reject) { var request = new _Misc_webRequest__WEBPACK_IMPORTED_MODULE_9__["WebRequest"](); request.addEventListener("readystatechange", function () { if (request.readyState == 4) { if (request.status == 200) { var snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload); if (snippet.animations) { var serializationObject = JSON.parse(snippet.animations); var output = new Array(); for (var _i = 0, serializationObject_2 = serializationObject; _i < serializationObject_2.length; _i++) { var serializedAnimation = serializationObject_2[_i]; output.push(_this.Parse(serializedAnimation)); } resolve(output); } else { var serializationObject = JSON.parse(snippet.animation); var output = _this.Parse(serializationObject); output.snippetId = snippetId; resolve(output); } } else { reject("Unable to load the snippet " + snippetId); } } }); request.open("GET", _this.SnippetUrl + "/" + snippetId.replace(/#/g, "/")); request.send(); }); }; /** * Use matrix interpolation instead of using direct key value when animating matrices */ Animation.AllowMatricesInterpolation = false; /** * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower */ Animation.AllowMatrixDecomposeForInterpolation = true; /** Define the Url to load snippets */ Animation.SnippetUrl = "https://snippet.babylonjs.com"; // Statics /** * Float animation type */ Animation.ANIMATIONTYPE_FLOAT = 0; /** * Vector3 animation type */ Animation.ANIMATIONTYPE_VECTOR3 = 1; /** * Quaternion animation type */ Animation.ANIMATIONTYPE_QUATERNION = 2; /** * Matrix animation type */ Animation.ANIMATIONTYPE_MATRIX = 3; /** * Color3 animation type */ Animation.ANIMATIONTYPE_COLOR3 = 4; /** * Color3 animation type */ Animation.ANIMATIONTYPE_COLOR4 = 7; /** * Vector2 animation type */ Animation.ANIMATIONTYPE_VECTOR2 = 5; /** * Size animation type */ Animation.ANIMATIONTYPE_SIZE = 6; /** * Relative Loop Mode */ Animation.ANIMATIONLOOPMODE_RELATIVE = 0; /** * Cycle Loop Mode */ Animation.ANIMATIONLOOPMODE_CYCLE = 1; /** * Constant Loop Mode */ Animation.ANIMATIONLOOPMODE_CONSTANT = 2; return Animation; }()); _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.Animation"] = Animation; _node__WEBPACK_IMPORTED_MODULE_7__["Node"]._AnimationRangeFactory = function (name, from, to) { return new _animationRange__WEBPACK_IMPORTED_MODULE_6__["AnimationRange"](name, from, to); }; /***/ }), /***/ "./Animations/animationEvent.ts": /*!**************************************!*\ !*** ./Animations/animationEvent.ts ***! \**************************************/ /*! exports provided: AnimationEvent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return AnimationEvent; }); /** * Composed of a frame, and an action function */ var AnimationEvent = /** @class */ (function () { /** * Initializes the animation event * @param frame The frame for which the event is triggered * @param action The event to perform when triggered * @param onlyOnce Specifies if the event should be triggered only once */ function AnimationEvent( /** The frame for which the event is triggered **/ frame, /** The event to perform when triggered **/ action, /** Specifies if the event should be triggered only once**/ onlyOnce) { this.frame = frame; this.action = action; this.onlyOnce = onlyOnce; /** * Specifies if the animation event is done */ this.isDone = false; } /** @hidden */ AnimationEvent.prototype._clone = function () { return new AnimationEvent(this.frame, this.action, this.onlyOnce); }; return AnimationEvent; }()); /***/ }), /***/ "./Animations/animationGroup.ts": /*!**************************************!*\ !*** ./Animations/animationGroup.ts ***! \**************************************/ /*! exports provided: TargetedAnimation, AnimationGroup */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return TargetedAnimation; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return AnimationGroup; }); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _animatable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./animatable */ "./Animations/animatable.ts"); /** * This class defines the direct association between an animation and a target */ var TargetedAnimation = /** @class */ (function () { function TargetedAnimation() { } /** * Returns the string "TargetedAnimation" * @returns "TargetedAnimation" */ TargetedAnimation.prototype.getClassName = function () { return "TargetedAnimation"; }; /** * Serialize the object * @returns the JSON object representing the current entity */ TargetedAnimation.prototype.serialize = function () { var serializationObject = {}; serializationObject.animation = this.animation.serialize(); serializationObject.targetId = this.target.id; return serializationObject; }; return TargetedAnimation; }()); /** * Use this class to create coordinated animations on multiple targets */ var AnimationGroup = /** @class */ (function () { /** * Instantiates a new Animation Group. * This helps managing several animations at once. * @see https://doc.babylonjs.com/how_to/group * @param name Defines the name of the group * @param scene Defines the scene the group belongs to */ function AnimationGroup( /** The name of the animation group */ name, scene) { if (scene === void 0) { scene = null; } this.name = name; this._targetedAnimations = new Array(); this._animatables = new Array(); this._from = Number.MAX_VALUE; this._to = -Number.MAX_VALUE; this._speedRatio = 1; this._loopAnimation = false; this._isAdditive = false; /** * This observable will notify when one animation have ended */ this.onAnimationEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observer raised when one animation loops */ this.onAnimationLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Observer raised when all animations have looped */ this.onAnimationGroupLoopObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * This observable will notify when all animations have ended. */ this.onAnimationGroupEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * This observable will notify when all animations have paused. */ this.onAnimationGroupPauseObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * This observable will notify when all animations are playing. */ this.onAnimationGroupPlayObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_2__["EngineStore"].LastCreatedScene; this.uniqueId = this._scene.getUniqueId(); this._scene.addAnimationGroup(this); } Object.defineProperty(AnimationGroup.prototype, "from", { /** * Gets the first frame */ get: function () { return this._from; }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "to", { /** * Gets the last frame */ get: function () { return this._to; }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "isStarted", { /** * Define if the animations are started */ get: function () { return this._isStarted; }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "isPlaying", { /** * Gets a value indicating that the current group is playing */ get: function () { return this._isStarted && !this._isPaused; }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "speedRatio", { /** * Gets or sets the speed ratio to use for all animations */ get: function () { return this._speedRatio; }, /** * Gets or sets the speed ratio to use for all animations */ set: function (value) { if (this._speedRatio === value) { return; } this._speedRatio = value; for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.speedRatio = this._speedRatio; } }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "loopAnimation", { /** * Gets or sets if all animations should loop or not */ get: function () { return this._loopAnimation; }, set: function (value) { if (this._loopAnimation === value) { return; } this._loopAnimation = value; for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.loopAnimation = this._loopAnimation; } }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "isAdditive", { /** * Gets or sets if all animations should be evaluated additively */ get: function () { return this._isAdditive; }, set: function (value) { if (this._isAdditive === value) { return; } this._isAdditive = value; for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.isAdditive = this._isAdditive; } }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", { /** * Gets the targeted animations for this animation group */ get: function () { return this._targetedAnimations; }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "animatables", { /** * returning the list of animatables controlled by this animation group. */ get: function () { return this._animatables; }, enumerable: false, configurable: true }); Object.defineProperty(AnimationGroup.prototype, "children", { /** * Gets the list of target animations */ get: function () { return this._targetedAnimations; }, enumerable: false, configurable: true }); /** * Add an animation (with its target) in the group * @param animation defines the animation we want to add * @param target defines the target of the animation * @returns the TargetedAnimation object */ AnimationGroup.prototype.addTargetedAnimation = function (animation, target) { var targetedAnimation = new TargetedAnimation(); targetedAnimation.animation = animation; targetedAnimation.target = target; var keys = animation.getKeys(); if (this._from > keys[0].frame) { this._from = keys[0].frame; } if (this._to < keys[keys.length - 1].frame) { this._to = keys[keys.length - 1].frame; } this._targetedAnimations.push(targetedAnimation); return targetedAnimation; }; /** * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame * It can add constant keys at begin or end * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null) * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null) * @returns the animation group */ AnimationGroup.prototype.normalize = function (beginFrame, endFrame) { if (beginFrame === void 0) { beginFrame = null; } if (endFrame === void 0) { endFrame = null; } if (beginFrame == null) { beginFrame = this._from; } if (endFrame == null) { endFrame = this._to; } for (var index = 0; index < this._targetedAnimations.length; index++) { var targetedAnimation = this._targetedAnimations[index]; var keys = targetedAnimation.animation.getKeys(); var startKey = keys[0]; var endKey = keys[keys.length - 1]; if (startKey.frame > beginFrame) { var newKey = { frame: beginFrame, value: startKey.value, inTangent: startKey.inTangent, outTangent: startKey.outTangent, interpolation: startKey.interpolation }; keys.splice(0, 0, newKey); } if (endKey.frame < endFrame) { var newKey = { frame: endFrame, value: endKey.value, inTangent: endKey.outTangent, outTangent: endKey.outTangent, interpolation: endKey.interpolation }; keys.push(newKey); } } this._from = beginFrame; this._to = endFrame; return this; }; AnimationGroup.prototype._processLoop = function (animatable, targetedAnimation, index) { var _this = this; animatable.onAnimationLoop = function () { _this.onAnimationLoopObservable.notifyObservers(targetedAnimation); if (_this._animationLoopFlags[index]) { return; } _this._animationLoopFlags[index] = true; _this._animationLoopCount++; if (_this._animationLoopCount === _this._targetedAnimations.length) { _this.onAnimationGroupLoopObservable.notifyObservers(_this); _this._animationLoopCount = 0; _this._animationLoopFlags = []; } }; }; /** * Start all animations on given targets * @param loop defines if animations must loop * @param speedRatio defines the ratio to apply to animation speed (1 by default) * @param from defines the from key (optional) * @param to defines the to key (optional) * @param isAdditive defines the additive state for the resulting animatables (optional) * @returns the current animation group */ AnimationGroup.prototype.start = function (loop, speedRatio, from, to, isAdditive) { var _this = this; if (loop === void 0) { loop = false; } if (speedRatio === void 0) { speedRatio = 1; } if (this._isStarted || this._targetedAnimations.length === 0) { return this; } this._loopAnimation = loop; this._animationLoopCount = 0; this._animationLoopFlags = []; var _loop_1 = function () { var targetedAnimation = this_1._targetedAnimations[index]; var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, undefined, undefined, isAdditive !== undefined ? isAdditive : this_1._isAdditive); animatable.onAnimationEnd = function () { _this.onAnimationEndObservable.notifyObservers(targetedAnimation); _this._checkAnimationGroupEnded(animatable); }; this_1._processLoop(animatable, targetedAnimation, index); this_1._animatables.push(animatable); }; var this_1 = this; for (var index = 0; index < this._targetedAnimations.length; index++) { _loop_1(); } this._speedRatio = speedRatio; if (from !== undefined && to !== undefined) { if (from < to && this._speedRatio < 0) { var temp = to; to = from; from = temp; } else if (from > to && this._speedRatio > 0) { this._speedRatio = -speedRatio; } } this._isStarted = true; this._isPaused = false; this.onAnimationGroupPlayObservable.notifyObservers(this); return this; }; /** * Pause all animations * @returns the animation group */ AnimationGroup.prototype.pause = function () { if (!this._isStarted) { return this; } this._isPaused = true; for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.pause(); } this.onAnimationGroupPauseObservable.notifyObservers(this); return this; }; /** * Play all animations to initial state * This function will start() the animations if they were not started or will restart() them if they were paused * @param loop defines if animations must loop * @returns the animation group */ AnimationGroup.prototype.play = function (loop) { // only if all animatables are ready and exist if (this.isStarted && this._animatables.length === this._targetedAnimations.length) { if (loop !== undefined) { this.loopAnimation = loop; } this.restart(); } else { this.stop(); this.start(loop, this._speedRatio); } this._isPaused = false; return this; }; /** * Reset all animations to initial state * @returns the animation group */ AnimationGroup.prototype.reset = function () { if (!this._isStarted) { this.play(); this.goToFrame(0); this.stop(); return this; } for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.reset(); } return this; }; /** * Restart animations from key 0 * @returns the animation group */ AnimationGroup.prototype.restart = function () { if (!this._isStarted) { return this; } for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.restart(); } this.onAnimationGroupPlayObservable.notifyObservers(this); return this; }; /** * Stop all animations * @returns the animation group */ AnimationGroup.prototype.stop = function () { if (!this._isStarted) { return this; } var list = this._animatables.slice(); for (var index = 0; index < list.length; index++) { list[index].stop(); } this._isStarted = false; return this; }; /** * Set animation weight for all animatables * @param weight defines the weight to use * @return the animationGroup * @see https://doc.babylonjs.com/babylon101/animations#animation-weights */ AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) { for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.weight = weight; } return this; }; /** * Synchronize and normalize all animatables with a source animatable * @param root defines the root animatable to synchronize with * @return the animationGroup * @see https://doc.babylonjs.com/babylon101/animations#animation-weights */ AnimationGroup.prototype.syncAllAnimationsWith = function (root) { for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.syncWith(root); } return this; }; /** * Goes to a specific frame in this animation group * @param frame the frame number to go to * @return the animationGroup */ AnimationGroup.prototype.goToFrame = function (frame) { if (!this._isStarted) { return this; } for (var index = 0; index < this._animatables.length; index++) { var animatable = this._animatables[index]; animatable.goToFrame(frame); } return this; }; /** * Dispose all associated resources */ AnimationGroup.prototype.dispose = function () { this._targetedAnimations = []; this._animatables = []; var index = this._scene.animationGroups.indexOf(this); if (index > -1) { this._scene.animationGroups.splice(index, 1); } this.onAnimationEndObservable.clear(); this.onAnimationGroupEndObservable.clear(); this.onAnimationGroupPauseObservable.clear(); this.onAnimationGroupPlayObservable.clear(); this.onAnimationLoopObservable.clear(); this.onAnimationGroupLoopObservable.clear(); }; AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) { // animatable should be taken out of the array var idx = this._animatables.indexOf(animatable); if (idx > -1) { this._animatables.splice(idx, 1); } // all animatables were removed? animation group ended! if (this._animatables.length === 0) { this._isStarted = false; this.onAnimationGroupEndObservable.notifyObservers(this); } }; /** * Clone the current animation group and returns a copy * @param newName defines the name of the new group * @param targetConverter defines an optional function used to convert current animation targets to new ones * @returns the new aniamtion group */ AnimationGroup.prototype.clone = function (newName, targetConverter) { var newGroup = new AnimationGroup(newName || this.name, this._scene); for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) { var targetAnimation = _a[_i]; newGroup.addTargetedAnimation(targetAnimation.animation.clone(), targetConverter ? targetConverter(targetAnimation.target) : targetAnimation.target); } return newGroup; }; /** * Serializes the animationGroup to an object * @returns Serialized object */ AnimationGroup.prototype.serialize = function () { var serializationObject = {}; serializationObject.name = this.name; serializationObject.from = this.from; serializationObject.to = this.to; serializationObject.targetedAnimations = []; for (var targetedAnimationIndex = 0; targetedAnimationIndex < this.targetedAnimations.length; targetedAnimationIndex++) { var targetedAnimation = this.targetedAnimations[targetedAnimationIndex]; serializationObject.targetedAnimations[targetedAnimationIndex] = targetedAnimation.serialize(); } return serializationObject; }; // Statics /** * Returns a new AnimationGroup object parsed from the source provided. * @param parsedAnimationGroup defines the source * @param scene defines the scene that will receive the animationGroup * @returns a new AnimationGroup */ AnimationGroup.Parse = function (parsedAnimationGroup, scene) { var animationGroup = new AnimationGroup(parsedAnimationGroup.name, scene); for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) { var targetedAnimation = parsedAnimationGroup.targetedAnimations[i]; var animation = _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].Parse(targetedAnimation.animation); var id = targetedAnimation.targetId; if (targetedAnimation.animation.property === "influence") { // morph target animation var morphTarget = scene.getMorphTargetById(id); if (morphTarget) { animationGroup.addTargetedAnimation(animation, morphTarget); } } else { var targetNode = scene.getNodeByID(id); if (targetNode != null) { animationGroup.addTargetedAnimation(animation, targetNode); } } } if (parsedAnimationGroup.from !== null && parsedAnimationGroup.to !== null) { animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to); } return animationGroup; }; /** * Convert the keyframes for all animations belonging to the group to be relative to a given reference frame. * @param sourceAnimationGroup defines the AnimationGroup containing animations to convert * @param referenceFrame defines the frame that keyframes in the range will be relative to * @param range defines the name of the AnimationRange belonging to the animations in the group to convert * @param cloneOriginal defines whether or not to clone the group and convert the clone or convert the original group (default is false) * @param clonedName defines the name of the resulting cloned AnimationGroup if cloneOriginal is true * @returns a new AnimationGroup if cloneOriginal is true or the original AnimationGroup if cloneOriginal is false */ AnimationGroup.MakeAnimationAdditive = function (sourceAnimationGroup, referenceFrame, range, cloneOriginal, clonedName) { if (referenceFrame === void 0) { referenceFrame = 0; } if (cloneOriginal === void 0) { cloneOriginal = false; } var animationGroup = sourceAnimationGroup; if (cloneOriginal) { animationGroup = sourceAnimationGroup.clone(clonedName || animationGroup.name); } var targetedAnimations = animationGroup.targetedAnimations; for (var index = 0; index < targetedAnimations.length; index++) { var targetedAnimation = targetedAnimations[index]; _animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].MakeAnimationAdditive(targetedAnimation.animation, referenceFrame, range); } animationGroup.isAdditive = true; return animationGroup; }; /** * Returns the string "AnimationGroup" * @returns "AnimationGroup" */ AnimationGroup.prototype.getClassName = function () { return "AnimationGroup"; }; /** * Creates a detailled string about the object * @param fullDetails defines if the output string will support multiple levels of logging within scene loading * @returns a string representing the object */ AnimationGroup.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name; ret += ", type: " + this.getClassName(); if (fullDetails) { ret += ", from: " + this._from; ret += ", to: " + this._to; ret += ", isStarted: " + this._isStarted; ret += ", speedRatio: " + this._speedRatio; ret += ", targetedAnimations length: " + this._targetedAnimations.length; ret += ", animatables length: " + this._animatables; } return ret; }; return AnimationGroup; }()); /***/ }), /***/ "./Animations/animationKey.ts": /*!************************************!*\ !*** ./Animations/animationKey.ts ***! \************************************/ /*! exports provided: AnimationKeyInterpolation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return AnimationKeyInterpolation; }); /** * Enum for the animation key frame interpolation type */ var AnimationKeyInterpolation; (function (AnimationKeyInterpolation) { /** * Do not interpolate between keys and use the start key value only. Tangents are ignored */ AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP"; })(AnimationKeyInterpolation || (AnimationKeyInterpolation = {})); /***/ }), /***/ "./Animations/animationPropertiesOverride.ts": /*!***************************************************!*\ !*** ./Animations/animationPropertiesOverride.ts ***! \***************************************************/ /*! exports provided: AnimationPropertiesOverride */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return AnimationPropertiesOverride; }); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); /** * Class used to override all child animations of a given target */ var AnimationPropertiesOverride = /** @class */ (function () { function AnimationPropertiesOverride() { /** * Gets or sets a value indicating if animation blending must be used */ this.enableBlending = false; /** * Gets or sets the blending speed to use when enableBlending is true */ this.blendingSpeed = 0.01; /** * Gets or sets the default loop mode to use */ this.loopMode = _Animations_animation__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONLOOPMODE_CYCLE; } return AnimationPropertiesOverride; }()); /***/ }), /***/ "./Animations/animationRange.ts": /*!**************************************!*\ !*** ./Animations/animationRange.ts ***! \**************************************/ /*! exports provided: AnimationRange */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return AnimationRange; }); /** * Represents the range of an animation */ var AnimationRange = /** @class */ (function () { /** * Initializes the range of an animation * @param name The name of the animation range * @param from The starting frame of the animation * @param to The ending frame of the animation */ function AnimationRange( /**The name of the animation range**/ name, /**The starting frame of the animation */ from, /**The ending frame of the animation*/ to) { this.name = name; this.from = from; this.to = to; } /** * Makes a copy of the animation range * @returns A copy of the animation range */ AnimationRange.prototype.clone = function () { return new AnimationRange(this.name, this.from, this.to); }; return AnimationRange; }()); /***/ }), /***/ "./Animations/easing.ts": /*!******************************!*\ !*** ./Animations/easing.ts ***! \******************************/ /*! exports provided: EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return EasingFunction; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return CircleEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return BackEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return BounceEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return CubicEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return ElasticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return ExponentialEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return PowerEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return QuadraticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return QuarticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return QuinticEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return SineEase; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return BezierCurveEase; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math_path__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.path */ "./Maths/math.path.ts"); /** * Base class used for every default easing function. * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var EasingFunction = /** @class */ (function () { function EasingFunction() { this._easingMode = EasingFunction.EASINGMODE_EASEIN; } /** * Sets the easing mode of the current function. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT) */ EasingFunction.prototype.setEasingMode = function (easingMode) { var n = Math.min(Math.max(easingMode, 0), 2); this._easingMode = n; }; /** * Gets the current easing mode. * @returns the easing mode */ EasingFunction.prototype.getEasingMode = function () { return this._easingMode; }; /** * @hidden */ EasingFunction.prototype.easeInCore = function (gradient) { throw new Error('You must implement this method'); }; /** * Given an input gradient between 0 and 1, this returns the corresponding value * of the easing function. * @param gradient Defines the value between 0 and 1 we want the easing value for * @returns the corresponding value on the curve defined by the easing function */ EasingFunction.prototype.ease = function (gradient) { switch (this._easingMode) { case EasingFunction.EASINGMODE_EASEIN: return this.easeInCore(gradient); case EasingFunction.EASINGMODE_EASEOUT: return (1 - this.easeInCore(1 - gradient)); } if (gradient >= 0.5) { return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5); } return (this.easeInCore(gradient * 2) * 0.5); }; /** * Interpolation follows the mathematical formula associated with the easing function. */ EasingFunction.EASINGMODE_EASEIN = 0; /** * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function. */ EasingFunction.EASINGMODE_EASEOUT = 1; /** * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half. */ EasingFunction.EASINGMODE_EASEINOUT = 2; return EasingFunction; }()); /** * Easing function with a circle shape (see link below). * @see https://easings.net/#easeInCirc * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var CircleEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CircleEase, _super); function CircleEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ CircleEase.prototype.easeInCore = function (gradient) { gradient = Math.max(0, Math.min(1, gradient)); return (1.0 - Math.sqrt(1.0 - (gradient * gradient))); }; return CircleEase; }(EasingFunction)); /** * Easing function with a ease back shape (see link below). * @see https://easings.net/#easeInBack * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var BackEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BackEase, _super); /** * Instantiates a back ease easing * @see https://easings.net/#easeInBack * @param amplitude Defines the amplitude of the function */ function BackEase( /** Defines the amplitude of the function */ amplitude) { if (amplitude === void 0) { amplitude = 1; } var _this = _super.call(this) || this; _this.amplitude = amplitude; return _this; } /** @hidden */ BackEase.prototype.easeInCore = function (gradient) { var num = Math.max(0, this.amplitude); return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient))); }; return BackEase; }(EasingFunction)); /** * Easing function with a bouncing shape (see link below). * @see https://easings.net/#easeInBounce * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var BounceEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BounceEase, _super); /** * Instantiates a bounce easing * @see https://easings.net/#easeInBounce * @param bounces Defines the number of bounces * @param bounciness Defines the amplitude of the bounce */ function BounceEase( /** Defines the number of bounces */ bounces, /** Defines the amplitude of the bounce */ bounciness) { if (bounces === void 0) { bounces = 3; } if (bounciness === void 0) { bounciness = 2; } var _this = _super.call(this) || this; _this.bounces = bounces; _this.bounciness = bounciness; return _this; } /** @hidden */ BounceEase.prototype.easeInCore = function (gradient) { var y = Math.max(0.0, this.bounces); var bounciness = this.bounciness; if (bounciness <= 1.0) { bounciness = 1.001; } var num9 = Math.pow(bounciness, y); var num5 = 1.0 - bounciness; var num4 = ((1.0 - num9) / num5) + (num9 * 0.5); var num15 = gradient * num4; var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness); var num3 = Math.floor(num65); var num13 = num3 + 1.0; var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4); var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4); var num7 = (num8 + num12) * 0.5; var num6 = gradient - num7; var num2 = num7 - num8; return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2)); }; return BounceEase; }(EasingFunction)); /** * Easing function with a power of 3 shape (see link below). * @see https://easings.net/#easeInCubic * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var CubicEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CubicEase, _super); function CubicEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ CubicEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient); }; return CubicEase; }(EasingFunction)); /** * Easing function with an elastic shape (see link below). * @see https://easings.net/#easeInElastic * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var ElasticEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ElasticEase, _super); /** * Instantiates an elastic easing function * @see https://easings.net/#easeInElastic * @param oscillations Defines the number of oscillations * @param springiness Defines the amplitude of the oscillations */ function ElasticEase( /** Defines the number of oscillations*/ oscillations, /** Defines the amplitude of the oscillations*/ springiness) { if (oscillations === void 0) { oscillations = 3; } if (springiness === void 0) { springiness = 3; } var _this = _super.call(this) || this; _this.oscillations = oscillations; _this.springiness = springiness; return _this; } /** @hidden */ ElasticEase.prototype.easeInCore = function (gradient) { var num2; var num3 = Math.max(0.0, this.oscillations); var num = Math.max(0.0, this.springiness); if (num == 0) { num2 = gradient; } else { num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0); } return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient)); }; return ElasticEase; }(EasingFunction)); /** * Easing function with an exponential shape (see link below). * @see https://easings.net/#easeInExpo * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var ExponentialEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExponentialEase, _super); /** * Instantiates an exponential easing function * @see https://easings.net/#easeInExpo * @param exponent Defines the exponent of the function */ function ExponentialEase( /** Defines the exponent of the function */ exponent) { if (exponent === void 0) { exponent = 2; } var _this = _super.call(this) || this; _this.exponent = exponent; return _this; } /** @hidden */ ExponentialEase.prototype.easeInCore = function (gradient) { if (this.exponent <= 0) { return gradient; } return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0)); }; return ExponentialEase; }(EasingFunction)); /** * Easing function with a power shape (see link below). * @see https://easings.net/#easeInQuad * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var PowerEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PowerEase, _super); /** * Instantiates an power base easing function * @see https://easings.net/#easeInQuad * @param power Defines the power of the function */ function PowerEase( /** Defines the power of the function */ power) { if (power === void 0) { power = 2; } var _this = _super.call(this) || this; _this.power = power; return _this; } /** @hidden */ PowerEase.prototype.easeInCore = function (gradient) { var y = Math.max(0.0, this.power); return Math.pow(gradient, y); }; return PowerEase; }(EasingFunction)); /** * Easing function with a power of 2 shape (see link below). * @see https://easings.net/#easeInQuad * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var QuadraticEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(QuadraticEase, _super); function QuadraticEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ QuadraticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient); }; return QuadraticEase; }(EasingFunction)); /** * Easing function with a power of 4 shape (see link below). * @see https://easings.net/#easeInQuart * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var QuarticEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(QuarticEase, _super); function QuarticEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ QuarticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient * gradient); }; return QuarticEase; }(EasingFunction)); /** * Easing function with a power of 5 shape (see link below). * @see https://easings.net/#easeInQuint * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var QuinticEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(QuinticEase, _super); function QuinticEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ QuinticEase.prototype.easeInCore = function (gradient) { return (gradient * gradient * gradient * gradient * gradient); }; return QuinticEase; }(EasingFunction)); /** * Easing function with a sin shape (see link below). * @see https://easings.net/#easeInSine * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var SineEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SineEase, _super); function SineEase() { return _super !== null && _super.apply(this, arguments) || this; } /** @hidden */ SineEase.prototype.easeInCore = function (gradient) { return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient))); }; return SineEase; }(EasingFunction)); /** * Easing function with a bezier shape (see link below). * @see http://cubic-bezier.com/#.17,.67,.83,.67 * @see https://doc.babylonjs.com/babylon101/animations#easing-functions */ var BezierCurveEase = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BezierCurveEase, _super); /** * Instantiates a bezier function * @see http://cubic-bezier.com/#.17,.67,.83,.67 * @param x1 Defines the x component of the start tangent in the bezier curve * @param y1 Defines the y component of the start tangent in the bezier curve * @param x2 Defines the x component of the end tangent in the bezier curve * @param y2 Defines the y component of the end tangent in the bezier curve */ function BezierCurveEase( /** Defines the x component of the start tangent in the bezier curve */ x1, /** Defines the y component of the start tangent in the bezier curve */ y1, /** Defines the x component of the end tangent in the bezier curve */ x2, /** Defines the y component of the end tangent in the bezier curve */ y2) { if (x1 === void 0) { x1 = 0; } if (y1 === void 0) { y1 = 0; } if (x2 === void 0) { x2 = 1; } if (y2 === void 0) { y2 = 1; } var _this = _super.call(this) || this; _this.x1 = x1; _this.y1 = y1; _this.x2 = x2; _this.y2 = y2; return _this; } /** @hidden */ BezierCurveEase.prototype.easeInCore = function (gradient) { return _Maths_math_path__WEBPACK_IMPORTED_MODULE_1__["BezierCurve"].Interpolate(gradient, this.x1, this.y1, this.x2, this.y2); }; return BezierCurveEase; }(EasingFunction)); /***/ }), /***/ "./Animations/index.ts": /*!*****************************!*\ !*** ./Animations/index.ts ***! \*****************************/ /*! exports provided: Animatable, _IAnimationState, Animation, TargetedAnimation, AnimationGroup, AnimationPropertiesOverride, EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase, RuntimeAnimation, AnimationEvent, AnimationKeyInterpolation, AnimationRange */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _animatable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./animatable */ "./Animations/animatable.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return _animatable__WEBPACK_IMPORTED_MODULE_0__["Animatable"]; }); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_IAnimationState", function() { return _animation__WEBPACK_IMPORTED_MODULE_1__["_IAnimationState"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _animation__WEBPACK_IMPORTED_MODULE_1__["Animation"]; }); /* harmony import */ var _animationGroup__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./animationGroup */ "./Animations/animationGroup.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return _animationGroup__WEBPACK_IMPORTED_MODULE_2__["TargetedAnimation"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return _animationGroup__WEBPACK_IMPORTED_MODULE_2__["AnimationGroup"]; }); /* harmony import */ var _animationPropertiesOverride__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./animationPropertiesOverride */ "./Animations/animationPropertiesOverride.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return _animationPropertiesOverride__WEBPACK_IMPORTED_MODULE_3__["AnimationPropertiesOverride"]; }); /* harmony import */ var _easing__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./easing */ "./Animations/easing.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["EasingFunction"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["CircleEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BackEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BounceEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["CubicEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["ElasticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["ExponentialEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["PowerEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuadraticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuarticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["QuinticEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["SineEase"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return _easing__WEBPACK_IMPORTED_MODULE_4__["BezierCurveEase"]; }); /* harmony import */ var _runtimeAnimation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./runtimeAnimation */ "./Animations/runtimeAnimation.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return _runtimeAnimation__WEBPACK_IMPORTED_MODULE_5__["RuntimeAnimation"]; }); /* harmony import */ var _animationEvent__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./animationEvent */ "./Animations/animationEvent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return _animationEvent__WEBPACK_IMPORTED_MODULE_6__["AnimationEvent"]; }); /* empty/unused harmony star reexport *//* harmony import */ var _animationKey__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./animationKey */ "./Animations/animationKey.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return _animationKey__WEBPACK_IMPORTED_MODULE_7__["AnimationKeyInterpolation"]; }); /* harmony import */ var _animationRange__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./animationRange */ "./Animations/animationRange.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return _animationRange__WEBPACK_IMPORTED_MODULE_8__["AnimationRange"]; }); /* harmony import */ var _animatable_interface__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./animatable.interface */ "./Animations/animatable.interface.ts"); /* empty/unused harmony star reexport */ /***/ }), /***/ "./Animations/runtimeAnimation.ts": /*!****************************************!*\ !*** ./Animations/runtimeAnimation.ts ***! \****************************************/ /*! exports provided: RuntimeAnimation */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return RuntimeAnimation; }); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts"); /* harmony import */ var _animation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./animation */ "./Animations/animation.ts"); /* harmony import */ var _Maths_math_size__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.size */ "./Maths/math.size.ts"); // Static values to help the garbage collector // Quaternion var _staticOffsetValueQuaternion = Object.freeze(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](0, 0, 0, 0)); // Vector3 var _staticOffsetValueVector3 = Object.freeze(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()); // Vector2 var _staticOffsetValueVector2 = Object.freeze(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero()); // Size var _staticOffsetValueSize = Object.freeze(_Maths_math_size__WEBPACK_IMPORTED_MODULE_3__["Size"].Zero()); // Color3 var _staticOffsetValueColor3 = Object.freeze(_Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color3"].Black()); /** * Defines a runtime animation */ var RuntimeAnimation = /** @class */ (function () { /** * Create a new RuntimeAnimation object * @param target defines the target of the animation * @param animation defines the source animation object * @param scene defines the hosting scene * @param host defines the initiating Animatable */ function RuntimeAnimation(target, animation, scene, host) { var _this = this; this._events = new Array(); /** * The current frame of the runtime animation */ this._currentFrame = 0; /** * The original value of the runtime animation */ this._originalValue = new Array(); /** * The original blend value of the runtime animation */ this._originalBlendValue = null; /** * The offsets cache of the runtime animation */ this._offsetsCache = {}; /** * The high limits cache of the runtime animation */ this._highLimitsCache = {}; /** * Specifies if the runtime animation has been stopped */ this._stopped = false; /** * The blending factor of the runtime animation */ this._blendingFactor = 0; /** * The current value of the runtime animation */ this._currentValue = null; this._currentActiveTarget = null; this._directTarget = null; /** * The target path of the runtime animation */ this._targetPath = ""; /** * The weight of the runtime animation */ this._weight = 1.0; /** * The ratio offset of the runtime animation */ this._ratioOffset = 0; /** * The previous delay of the runtime animation */ this._previousDelay = 0; /** * The previous ratio of the runtime animation */ this._previousRatio = 0; this._targetIsArray = false; this._animation = animation; this._target = target; this._scene = scene; this._host = host; this._activeTargets = []; animation._runtimeAnimations.push(this); // State this._animationState = { key: 0, repeatCount: 0, loopMode: this._getCorrectLoopMode() }; if (this._animation.dataType === _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_MATRIX) { this._animationState.workValue = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Zero(); } // Limits this._keys = this._animation.getKeys(); this._minFrame = this._keys[0].frame; this._maxFrame = this._keys[this._keys.length - 1].frame; this._minValue = this._keys[0].value; this._maxValue = this._keys[this._keys.length - 1].value; // Add a start key at frame 0 if missing if (this._minFrame !== 0) { var newKey = { frame: 0, value: this._minValue }; this._keys.splice(0, 0, newKey); } // Check data if (this._target instanceof Array) { var index = 0; for (var _i = 0, _a = this._target; _i < _a.length; _i++) { var target_1 = _a[_i]; this._preparePath(target_1, index); this._getOriginalValues(index); index++; } this._targetIsArray = true; } else { this._preparePath(this._target); this._getOriginalValues(); this._targetIsArray = false; this._directTarget = this._activeTargets[0]; } // Cloning events locally var events = animation.getEvents(); if (events && events.length > 0) { events.forEach(function (e) { _this._events.push(e._clone()); }); } this._enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending; } Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", { /** * Gets the current frame of the runtime animation */ get: function () { return this._currentFrame; }, enumerable: false, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "weight", { /** * Gets the weight of the runtime animation */ get: function () { return this._weight; }, enumerable: false, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "currentValue", { /** * Gets the current value of the runtime animation */ get: function () { return this._currentValue; }, enumerable: false, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "targetPath", { /** * Gets the target path of the runtime animation */ get: function () { return this._targetPath; }, enumerable: false, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "target", { /** * Gets the actual target of the runtime animation */ get: function () { return this._currentActiveTarget; }, enumerable: false, configurable: true }); Object.defineProperty(RuntimeAnimation.prototype, "isAdditive", { /** * Gets the additive state of the runtime animation */ get: function () { return this._host && this._host.isAdditive; }, enumerable: false, configurable: true }); RuntimeAnimation.prototype._preparePath = function (target, targetIndex) { if (targetIndex === void 0) { targetIndex = 0; } var targetPropertyPath = this._animation.targetPropertyPath; if (targetPropertyPath.length > 1) { var property = target[targetPropertyPath[0]]; for (var index = 1; index < targetPropertyPath.length - 1; index++) { property = property[targetPropertyPath[index]]; } this._targetPath = targetPropertyPath[targetPropertyPath.length - 1]; this._activeTargets[targetIndex] = property; } else { this._targetPath = targetPropertyPath[0]; this._activeTargets[targetIndex] = target; } }; Object.defineProperty(RuntimeAnimation.prototype, "animation", { /** * Gets the animation from the runtime animation */ get: function () { return this._animation; }, enumerable: false, configurable: true }); /** * Resets the runtime animation to the beginning * @param restoreOriginal defines whether to restore the target property to the original value */ RuntimeAnimation.prototype.reset = function (restoreOriginal) { if (restoreOriginal === void 0) { restoreOriginal = false; } if (restoreOriginal) { if (this._target instanceof Array) { var index = 0; for (var _i = 0, _a = this._target; _i < _a.length; _i++) { var target = _a[_i]; if (this._originalValue[index] !== undefined) { this._setValue(target, this._activeTargets[index], this._originalValue[index], -1, index); } index++; } } else { if (this._originalValue[0] !== undefined) { this._setValue(this._target, this._directTarget, this._originalValue[0], -1, 0); } } } this._offsetsCache = {}; this._highLimitsCache = {}; this._currentFrame = 0; this._blendingFactor = 0; // Events for (var index = 0; index < this._events.length; index++) { this._events[index].isDone = false; } }; /** * Specifies if the runtime animation is stopped * @returns Boolean specifying if the runtime animation is stopped */ RuntimeAnimation.prototype.isStopped = function () { return this._stopped; }; /** * Disposes of the runtime animation */ RuntimeAnimation.prototype.dispose = function () { var index = this._animation.runtimeAnimations.indexOf(this); if (index > -1) { this._animation.runtimeAnimations.splice(index, 1); } }; /** * Apply the interpolated value to the target * @param currentValue defines the value computed by the animation * @param weight defines the weight to apply to this value (Defaults to 1.0) */ RuntimeAnimation.prototype.setValue = function (currentValue, weight) { if (this._targetIsArray) { for (var index = 0; index < this._target.length; index++) { var target = this._target[index]; this._setValue(target, this._activeTargets[index], currentValue, weight, index); } return; } this._setValue(this._target, this._directTarget, currentValue, weight, 0); }; RuntimeAnimation.prototype._getOriginalValues = function (targetIndex) { if (targetIndex === void 0) { targetIndex = 0; } var originalValue; var target = this._activeTargets[targetIndex]; if (target.getRestPose && this._targetPath === "_matrix") { // For bones originalValue = target.getRestPose(); } else { originalValue = target[this._targetPath]; } if (originalValue && originalValue.clone) { this._originalValue[targetIndex] = originalValue.clone(); } else { this._originalValue[targetIndex] = originalValue; } }; RuntimeAnimation.prototype._setValue = function (target, destination, currentValue, weight, targetIndex) { // Set value this._currentActiveTarget = destination; this._weight = weight; if (this._enableBlending && this._blendingFactor <= 1.0) { if (!this._originalBlendValue) { var originalValue = destination[this._targetPath]; if (originalValue.clone) { this._originalBlendValue = originalValue.clone(); } else { this._originalBlendValue = originalValue; } } if (this._originalBlendValue.m) { // Matrix if (_animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].AllowMatrixDecomposeForInterpolation) { if (this._currentValue) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); } else { this._currentValue = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor); } } else { if (this._currentValue) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue); } else { this._currentValue = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Lerp(this._originalBlendValue, currentValue, this._blendingFactor); } } } else { this._currentValue = _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"]._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor); } var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed; this._blendingFactor += blendingSpeed; } else { this._currentValue = currentValue; } if (weight !== -1.0) { this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]); } else { destination[this._targetPath] = this._currentValue; } if (target.markAsDirty) { target.markAsDirty(this._animation.targetProperty); } }; /** * Gets the loop pmode of the runtime animation * @returns Loop Mode */ RuntimeAnimation.prototype._getCorrectLoopMode = function () { if (this._target && this._target.animationPropertiesOverride) { return this._target.animationPropertiesOverride.loopMode; } return this._animation.loopMode; }; /** * Move the current animation to a given frame * @param frame defines the frame to move to */ RuntimeAnimation.prototype.goToFrame = function (frame) { var keys = this._animation.getKeys(); if (frame < keys[0].frame) { frame = keys[0].frame; } else if (frame > keys[keys.length - 1].frame) { frame = keys[keys.length - 1].frame; } // Need to reset animation events var events = this._events; if (events.length) { for (var index = 0; index < events.length; index++) { if (!events[index].onlyOnce) { // reset events in the future events[index].isDone = events[index].frame < frame; } } } this._currentFrame = frame; var currentValue = this._animation._interpolate(frame, this._animationState); this.setValue(currentValue, -1); }; /** * @hidden Internal use only */ RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) { var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0; this._ratioOffset = this._previousRatio - newRatio; }; /** * Execute the current animation * @param delay defines the delay to add to the current frame * @param from defines the lower bound of the animation range * @param to defines the upper bound of the animation range * @param loop defines if the current animation must loop * @param speedRatio defines the current speed ratio * @param weight defines the weight of the animation (default is -1 so no weight) * @param onLoop optional callback called when animation loops * @returns a boolean indicating if the animation is running */ RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) { if (weight === void 0) { weight = -1.0; } var animation = this._animation; var targetPropertyPath = animation.targetPropertyPath; if (!targetPropertyPath || targetPropertyPath.length < 1) { this._stopped = true; return false; } var returnValue = true; // Check limits if (from < this._minFrame || from > this._maxFrame) { from = this._minFrame; } if (to < this._minFrame || to > this._maxFrame) { to = this._maxFrame; } var range = to - from; var offsetValue; // Compute ratio which represents the frame delta between from and to var ratio = (delay * (animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset; var highLimitValue = 0; this._previousDelay = delay; this._previousRatio = ratio; if (!loop && (to >= from && ratio >= range)) { // If we are out of range and not looping get back to caller returnValue = false; highLimitValue = animation._getKeyValue(this._maxValue); } else if (!loop && (from >= to && ratio <= range)) { returnValue = false; highLimitValue = animation._getKeyValue(this._minValue); } else if (this._animationState.loopMode !== _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONLOOPMODE_CYCLE) { var keyOffset = to.toString() + from.toString(); if (!this._offsetsCache[keyOffset]) { this._animationState.repeatCount = 0; this._animationState.loopMode = _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONLOOPMODE_CYCLE; var fromValue = animation._interpolate(from, this._animationState); var toValue = animation._interpolate(to, this._animationState); this._animationState.loopMode = this._getCorrectLoopMode(); switch (animation.dataType) { // Float case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_FLOAT: this._offsetsCache[keyOffset] = toValue - fromValue; break; // Quaternion case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_QUATERNION: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); break; // Vector3 case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_VECTOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Vector2 case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_VECTOR2: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Size case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_SIZE: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); // Color3 case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_COLOR3: this._offsetsCache[keyOffset] = toValue.subtract(fromValue); default: break; } this._highLimitsCache[keyOffset] = toValue; } highLimitValue = this._highLimitsCache[keyOffset]; offsetValue = this._offsetsCache[keyOffset]; } if (offsetValue === undefined) { switch (animation.dataType) { // Float case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_FLOAT: offsetValue = 0; break; // Quaternion case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_QUATERNION: offsetValue = _staticOffsetValueQuaternion; break; // Vector3 case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_VECTOR3: offsetValue = _staticOffsetValueVector3; break; // Vector2 case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_VECTOR2: offsetValue = _staticOffsetValueVector2; break; // Size case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_SIZE: offsetValue = _staticOffsetValueSize; break; // Color3 case _animation__WEBPACK_IMPORTED_MODULE_2__["Animation"].ANIMATIONTYPE_COLOR3: offsetValue = _staticOffsetValueColor3; } } // Compute value var currentFrame; if (this._host && this._host.syncRoot) { var syncRoot = this._host.syncRoot; var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame); currentFrame = from + (to - from) * hostNormalizedFrame; } else { currentFrame = (returnValue && range !== 0) ? from + ratio % range : to; } // Reset events if looping var events = this._events; if (range > 0 && this.currentFrame > currentFrame || range < 0 && this.currentFrame < currentFrame) { this._onLoop(); // Need to reset animation events if (events.length) { for (var index = 0; index < events.length; index++) { if (!events[index].onlyOnce) { // reset event, the animation is looping events[index].isDone = false; } } } } this._currentFrame = currentFrame; this._animationState.repeatCount = range === 0 ? 0 : (ratio / range) >> 0; this._animationState.highLimitValue = highLimitValue; this._animationState.offsetValue = offsetValue; var currentValue = animation._interpolate(currentFrame, this._animationState); // Set value this.setValue(currentValue, weight); // Check events if (events.length) { for (var index = 0; index < events.length; index++) { // Make sure current frame has passed event frame and that event frame is within the current range // Also, handle both forward and reverse animations if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) || (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) { var event = events[index]; if (!event.isDone) { // If event should be done only once, remove it. if (event.onlyOnce) { events.splice(index, 1); index--; } event.isDone = true; event.action(currentFrame); } // Don't do anything if the event has already be done. } } } if (!returnValue) { this._stopped = true; } return returnValue; }; return RuntimeAnimation; }()); /***/ }), /***/ "./Audio/analyser.ts": /*!***************************!*\ !*** ./Audio/analyser.ts ***! \***************************/ /*! exports provided: Analyser */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return Analyser; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /** * Class used to work with sound analyzer using fast fourier transform (FFT) * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music */ var Analyser = /** @class */ (function () { /** * Creates a new analyser * @param scene defines hosting scene */ function Analyser(scene) { /** * Gets or sets the smoothing * @ignorenaming */ this.SMOOTHING = 0.75; /** * Gets or sets the FFT table size * @ignorenaming */ this.FFT_SIZE = 512; /** * Gets or sets the bar graph amplitude * @ignorenaming */ this.BARGRAPHAMPLITUDE = 256; /** * Gets or sets the position of the debug canvas * @ignorenaming */ this.DEBUGCANVASPOS = { x: 20, y: 20 }; /** * Gets or sets the debug canvas size * @ignorenaming */ this.DEBUGCANVASSIZE = { width: 320, height: 200 }; this._scene = scene; this._audioEngine = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine; if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) { this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser(); this._webAudioAnalyser.minDecibels = -140; this._webAudioAnalyser.maxDecibels = 0; this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount); this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount); } } /** * Get the number of data values you will have to play with for the visualization * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount * @returns a number */ Analyser.prototype.getFrequencyBinCount = function () { if (this._audioEngine.canUseWebAudio) { return this._webAudioAnalyser.frequencyBinCount; } else { return 0; } }; /** * Gets the current frequency data as a byte array * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData * @returns a Uint8Array */ Analyser.prototype.getByteFrequencyData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs); } return this._byteFreqs; }; /** * Gets the current waveform as a byte array * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData * @returns a Uint8Array */ Analyser.prototype.getByteTimeDomainData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getByteTimeDomainData(this._byteTime); } return this._byteTime; }; /** * Gets the current frequency data as a float array * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData * @returns a Float32Array */ Analyser.prototype.getFloatFrequencyData = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING; this._webAudioAnalyser.fftSize = this.FFT_SIZE; this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs); } return this._floatFreqs; }; /** * Renders the debug canvas */ Analyser.prototype.drawDebugCanvas = function () { var _this = this; if (this._audioEngine.canUseWebAudio) { if (!this._debugCanvas) { this._debugCanvas = document.createElement("canvas"); this._debugCanvas.width = this.DEBUGCANVASSIZE.width; this._debugCanvas.height = this.DEBUGCANVASSIZE.height; this._debugCanvas.style.position = "absolute"; this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px"; this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px"; this._debugCanvasContext = this._debugCanvas.getContext("2d"); document.body.appendChild(this._debugCanvas); this._registerFunc = function () { _this.drawDebugCanvas(); }; this._scene.registerBeforeRender(this._registerFunc); } if (this._registerFunc && this._debugCanvasContext) { var workingArray = this.getByteFrequencyData(); this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)'; this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height); // Draw the frequency domain chart. for (var i = 0; i < this.getFrequencyBinCount(); i++) { var value = workingArray[i]; var percent = value / this.BARGRAPHAMPLITUDE; var height = this.DEBUGCANVASSIZE.height * percent; var offset = this.DEBUGCANVASSIZE.height - height - 1; var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount(); var hue = i / this.getFrequencyBinCount() * 360; this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)'; this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height); } } } }; /** * Stops rendering the debug canvas and removes it */ Analyser.prototype.stopDebugCanvas = function () { if (this._debugCanvas) { if (this._registerFunc) { this._scene.unregisterBeforeRender(this._registerFunc); this._registerFunc = null; } document.body.removeChild(this._debugCanvas); this._debugCanvas = null; this._debugCanvasContext = null; } }; /** * Connects two audio nodes * @param inputAudioNode defines first node to connect * @param outputAudioNode defines second node to connect */ Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) { if (this._audioEngine.canUseWebAudio) { inputAudioNode.connect(this._webAudioAnalyser); this._webAudioAnalyser.connect(outputAudioNode); } }; /** * Releases all associated resources */ Analyser.prototype.dispose = function () { if (this._audioEngine.canUseWebAudio) { this._webAudioAnalyser.disconnect(); } }; return Analyser; }()); /***/ }), /***/ "./Audio/audioEngine.ts": /*!******************************!*\ !*** ./Audio/audioEngine.ts ***! \******************************/ /*! exports provided: AudioEngine */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return AudioEngine; }); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); // Sets the default audio engine to Babylon.js _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); }; /** * This represents the default audio engine used in babylon. * It is responsible to play, synchronize and analyse sounds throughout the application. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music */ var AudioEngine = /** @class */ (function () { /** * Instantiates a new audio engine. * * There should be only one per page as some browsers restrict the number * of audio contexts you can create. * @param hostElement defines the host element where to display the mute icon if necessary */ function AudioEngine(hostElement) { var _this = this; if (hostElement === void 0) { hostElement = null; } this._audioContext = null; this._audioContextInitialized = false; this._muteButton = null; /** * Gets whether the current host supports Web Audio and thus could create AudioContexts. */ this.canUseWebAudio = false; /** * Defines if Babylon should emit a warning if WebAudio is not supported. * @ignoreNaming */ this.WarnedWebAudioUnsupported = false; /** * Gets whether or not mp3 are supported by your browser. */ this.isMP3supported = false; /** * Gets whether or not ogg are supported by your browser. */ this.isOGGsupported = false; /** * Gets whether audio has been unlocked on the device. * Some Browsers have strong restrictions about Audio and won t autoplay unless * a user interaction has happened. */ this.unlocked = true; /** * Defines if the audio engine relies on a custom unlocked button. * In this case, the embedded button will not be displayed. */ this.useCustomUnlockedButton = false; /** * Event raised when audio has been unlocked on the browser. */ this.onAudioUnlockedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); /** * Event raised when audio has been locked on the browser. */ this.onAudioLockedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](); this._tryToRun = false; this._onResize = function () { _this._moveButtonToTopLeft(); }; if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') { window.AudioContext = window.AudioContext || window.webkitAudioContext; this.canUseWebAudio = true; } var audioElem = document.createElement('audio'); this._hostElement = hostElement; try { if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) { this.isMP3supported = true; } } catch (e) { // protect error during capability check. } try { if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) { this.isOGGsupported = true; } } catch (e) { // protect error during capability check. } } Object.defineProperty(AudioEngine.prototype, "audioContext", { /** * Gets the current AudioContext if available. */ get: function () { if (!this._audioContextInitialized) { this._initializeAudioContext(); } else { if (!this.unlocked && !this._muteButton) { this._displayMuteButton(); } } return this._audioContext; }, enumerable: false, configurable: true }); /** * Flags the audio engine in Locked state. * This happens due to new browser policies preventing audio to autoplay. */ AudioEngine.prototype.lock = function () { this._triggerSuspendedState(); }; /** * Unlocks the audio engine once a user action has been done on the dom. * This is helpful to resume play once browser policies have been satisfied. */ AudioEngine.prototype.unlock = function () { this._triggerRunningState(); }; AudioEngine.prototype._resumeAudioContext = function () { var result; if (this._audioContext.resume !== undefined) { result = this._audioContext.resume(); } return result || Promise.resolve(); }; AudioEngine.prototype._initializeAudioContext = function () { try { if (this.canUseWebAudio) { this._audioContext = new AudioContext(); // create a global volume gain node this.masterGain = this._audioContext.createGain(); this.masterGain.gain.value = 1; this.masterGain.connect(this._audioContext.destination); this._audioContextInitialized = true; if (this._audioContext.state === "running") { // Do not wait for the promise to unlock. this._triggerRunningState(); } } } catch (e) { this.canUseWebAudio = false; _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Web Audio: " + e.message); } }; AudioEngine.prototype._triggerRunningState = function () { var _this = this; if (this._tryToRun) { return; } this._tryToRun = true; this._resumeAudioContext() .then(function () { _this._tryToRun = false; if (_this._muteButton) { _this._hideMuteButton(); } // Notify users that the audio stack is unlocked/unmuted _this.unlocked = true; _this.onAudioUnlockedObservable.notifyObservers(_this); }).catch(function () { _this._tryToRun = false; _this.unlocked = false; }); }; AudioEngine.prototype._triggerSuspendedState = function () { this.unlocked = false; this.onAudioLockedObservable.notifyObservers(this); this._displayMuteButton(); }; AudioEngine.prototype._displayMuteButton = function () { var _this = this; if (this.useCustomUnlockedButton || this._muteButton) { return; } this._muteButton = document.createElement("BUTTON"); this._muteButton.className = "babylonUnmuteIcon"; this._muteButton.id = "babylonUnmuteIconBtn"; this._muteButton.title = "Unmute"; var imageUrl = !window.SVGSVGElement ? "https://cdn.babylonjs.com/Assets/audio.png" : "data:image/svg+xml;charset=UTF-8,%3Csvg%20version%3D%221.1%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2239%22%20height%3D%2232%22%20viewBox%3D%220%200%2039%2032%22%3E%3Cpath%20fill%3D%22white%22%20d%3D%22M9.625%2018.938l-0.031%200.016h-4.953q-0.016%200-0.031-0.016v-12.453q0-0.016%200.031-0.016h4.953q0.031%200%200.031%200.016v12.453zM12.125%207.688l8.719-8.703v27.453l-8.719-8.719-0.016-0.047v-9.938zM23.359%207.875l1.406-1.406%204.219%204.203%204.203-4.203%201.422%201.406-4.219%204.219%204.219%204.203-1.484%201.359-4.141-4.156-4.219%204.219-1.406-1.422%204.219-4.203z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E"; var css = ".babylonUnmuteIcon { position: absolute; left: 20px; top: 20px; height: 40px; width: 60px; background-color: rgba(51,51,51,0.7); background-image: url(" + imageUrl + "); background-size: 80%; background-repeat:no-repeat; background-position: center; background-position-y: 4px; border: none; outline: none; transition: transform 0.125s ease-out; cursor: pointer; z-index: 9999; } .babylonUnmuteIcon:hover { transform: scale(1.05) } .babylonUnmuteIcon:active { background-color: rgba(51,51,51,1) }"; var style = document.createElement('style'); style.appendChild(document.createTextNode(css)); document.getElementsByTagName('head')[0].appendChild(style); document.body.appendChild(this._muteButton); this._moveButtonToTopLeft(); this._muteButton.addEventListener('touchend', function () { _this._triggerRunningState(); }, true); this._muteButton.addEventListener('click', function () { _this._triggerRunningState(); }, true); window.addEventListener("resize", this._onResize); }; AudioEngine.prototype._moveButtonToTopLeft = function () { if (this._hostElement && this._muteButton) { this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px"; this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px"; } }; AudioEngine.prototype._hideMuteButton = function () { if (this._muteButton) { document.body.removeChild(this._muteButton); this._muteButton = null; } }; /** * Destroy and release the resources associated with the audio ccontext. */ AudioEngine.prototype.dispose = function () { if (this.canUseWebAudio && this._audioContextInitialized) { if (this._connectedAnalyser && this._audioContext) { this._connectedAnalyser.stopDebugCanvas(); this._connectedAnalyser.dispose(); this.masterGain.disconnect(); this.masterGain.connect(this._audioContext.destination); this._connectedAnalyser = null; } this.masterGain.gain.value = 1; } this.WarnedWebAudioUnsupported = false; this._hideMuteButton(); window.removeEventListener("resize", this._onResize); this.onAudioUnlockedObservable.clear(); this.onAudioLockedObservable.clear(); }; /** * Gets the global volume sets on the master gain. * @returns the global volume if set or -1 otherwise */ AudioEngine.prototype.getGlobalVolume = function () { if (this.canUseWebAudio && this._audioContextInitialized) { return this.masterGain.gain.value; } else { return -1; } }; /** * Sets the global volume of your experience (sets on the master gain). * @param newVolume Defines the new global volume of the application */ AudioEngine.prototype.setGlobalVolume = function (newVolume) { if (this.canUseWebAudio && this._audioContextInitialized) { this.masterGain.gain.value = newVolume; } }; /** * Connect the audio engine to an audio analyser allowing some amazing * synchornization between the sounds/music and your visualization (VuMeter for instance). * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser * @param analyser The analyser to connect to the engine */ AudioEngine.prototype.connectToAnalyser = function (analyser) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) { this._connectedAnalyser = analyser; this.masterGain.disconnect(); this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination); } }; return AudioEngine; }()); /***/ }), /***/ "./Audio/audioSceneComponent.ts": /*!**************************************!*\ !*** ./Audio/audioSceneComponent.ts ***! \**************************************/ /*! exports provided: AudioSceneComponent */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return AudioSceneComponent; }); /* harmony import */ var _sound__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sound */ "./Audio/sound.ts"); /* harmony import */ var _soundTrack__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./soundTrack */ "./Audio/soundTrack.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../scene */ "./scene.ts"); /* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts"); /* harmony import */ var _audioEngine__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./audioEngine */ "./Audio/audioEngine.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/precisionDate */ "./Misc/precisionDate.ts"); // Adds the parser to the scene parsers. _abstractScene__WEBPACK_IMPORTED_MODULE_6__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO, function (parsedData, scene, container, rootUrl) { // TODO: add sound var loadedSounds = []; var loadedSound; container.sounds = container.sounds || []; if (parsedData.sounds !== undefined && parsedData.sounds !== null) { for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) { var parsedSound = parsedData.sounds[index]; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.canUseWebAudio) { if (!parsedSound.url) { parsedSound.url = parsedSound.name; } if (!loadedSounds[parsedSound.url]) { loadedSound = _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"].Parse(parsedSound, scene, rootUrl); loadedSounds[parsedSound.url] = loadedSound; container.sounds.push(loadedSound); } else { container.sounds.push(_sound__WEBPACK_IMPORTED_MODULE_0__["Sound"].Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url])); } } else { container.sounds.push(new _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"](parsedSound.name, null, scene)); } } } loadedSounds = []; }); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "mainSoundTrack", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (!this._mainSoundTrack) { this._mainSoundTrack = new _soundTrack__WEBPACK_IMPORTED_MODULE_1__["SoundTrack"](this, { mainTrack: true }); } return this._mainSoundTrack; }, enumerable: true, configurable: true }); _scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype.getSoundByName = function (name) { var index; for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) { if (this.mainSoundTrack.soundCollection[index].name === name) { return this.mainSoundTrack.soundCollection[index]; } } if (this.soundTracks) { for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) { for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) { if (this.soundTracks[sdIndex].soundCollection[index].name === name) { return this.soundTracks[sdIndex].soundCollection[index]; } } } } return null; }; Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "audioEnabled", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } return compo.audioEnabled; }, set: function (value) { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (value) { compo.enableAudio(); } else { compo.disableAudio(); } }, enumerable: true, configurable: true }); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "headphone", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } return compo.headphone; }, set: function (value) { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (value) { compo.switchAudioModeForHeadphones(); } else { compo.switchAudioModeForNormalSpeakers(); } }, enumerable: true, configurable: true }); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "audioListenerPositionProvider", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } return compo.audioListenerPositionProvider; }, set: function (value) { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } if (typeof value !== 'function') { throw new Error('The value passed to [Scene.audioListenerPositionProvider] must be a function that returns a Vector3'); } else { compo.audioListenerPositionProvider = value; } }, enumerable: true, configurable: true }); Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].prototype, "audioPositioningRefreshRate", { get: function () { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } return compo.audioPositioningRefreshRate; }, set: function (value) { var compo = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(this); this._addComponent(compo); } compo.audioPositioningRefreshRate = value; }, enumerable: true, configurable: true }); /** * Defines the sound scene component responsible to manage any sounds * in a given scene. */ var AudioSceneComponent = /** @class */ (function () { /** * Creates a new instance of the component for the given scene * @param scene Defines the scene to register the component in */ function AudioSceneComponent(scene) { /** * The component name helpfull to identify the component in the list of scene components. */ this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO; this._audioEnabled = true; this._headphone = false; /** * Gets or sets a refresh rate when using 3D audio positioning */ this.audioPositioningRefreshRate = 500; this._audioListenerPositionProvider = null; this._cachedCameraDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); this._cachedCameraPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); this._lastCheck = 0; this.scene = scene; scene.soundTracks = new Array(); scene.sounds = new Array(); } Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", { /** * Gets whether audio is enabled or not. * Please use related enable/disable method to switch state. */ get: function () { return this._audioEnabled; }, enumerable: false, configurable: true }); Object.defineProperty(AudioSceneComponent.prototype, "headphone", { /** * Gets whether audio is outputing to headphone or not. * Please use the according Switch methods to change output. */ get: function () { return this._headphone; }, enumerable: false, configurable: true }); Object.defineProperty(AudioSceneComponent.prototype, "audioListenerPositionProvider", { /** * Gets the current audio listener position provider */ get: function () { return this._audioListenerPositionProvider; }, /** * Sets a custom listener position for all sounds in the scene * By default, this is the position of the first active camera */ set: function (value) { this._audioListenerPositionProvider = value; }, enumerable: false, configurable: true }); /** * Registers the component in a given scene */ AudioSceneComponent.prototype.register = function () { this.scene._afterRenderStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].STEP_AFTERRENDER_AUDIO, this, this._afterRender); }; /** * Rebuilds the elements related to this component in case of * context lost for instance. */ AudioSceneComponent.prototype.rebuild = function () { // Nothing to do here. (Not rendering related) }; /** * Serializes the component data to the specified json object * @param serializationObject The object to serialize to */ AudioSceneComponent.prototype.serialize = function (serializationObject) { serializationObject.sounds = []; if (this.scene.soundTracks) { for (var index = 0; index < this.scene.soundTracks.length; index++) { var soundtrack = this.scene.soundTracks[index]; for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) { serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize()); } } } }; /** * Adds all the elements from the container to the scene * @param container the container holding the elements */ AudioSceneComponent.prototype.addFromContainer = function (container) { var _this = this; if (!container.sounds) { return; } container.sounds.forEach(function (sound) { sound.play(); sound.autoplay = true; _this.scene.mainSoundTrack.AddSound(sound); }); }; /** * Removes all the elements in the container from the scene * @param container contains the elements to remove * @param dispose if the removed element should be disposed (default: false) */ AudioSceneComponent.prototype.removeFromContainer = function (container, dispose) { var _this = this; if (dispose === void 0) { dispose = false; } if (!container.sounds) { return; } container.sounds.forEach(function (sound) { sound.stop(); sound.autoplay = false; _this.scene.mainSoundTrack.RemoveSound(sound); if (dispose) { sound.dispose(); } }); }; /** * Disposes the component and the associated ressources. */ AudioSceneComponent.prototype.dispose = function () { var scene = this.scene; if (scene._mainSoundTrack) { scene.mainSoundTrack.dispose(); } if (scene.soundTracks) { for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) { scene.soundTracks[scIndex].dispose(); } } }; /** * Disables audio in the associated scene. */ AudioSceneComponent.prototype.disableAudio = function () { var scene = this.scene; this._audioEnabled = false; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine && _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.audioContext) { _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.audioContext.suspend(); } var i; for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { scene.mainSoundTrack.soundCollection[i].pause(); } if (scene.soundTracks) { for (i = 0; i < scene.soundTracks.length; i++) { for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { scene.soundTracks[i].soundCollection[j].pause(); } } } }; /** * Enables audio in the associated scene. */ AudioSceneComponent.prototype.enableAudio = function () { var scene = this.scene; this._audioEnabled = true; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine && _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.audioContext) { _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine.audioContext.resume(); } var i; for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { if (scene.mainSoundTrack.soundCollection[i].isPaused) { scene.mainSoundTrack.soundCollection[i].play(); } } if (scene.soundTracks) { for (i = 0; i < scene.soundTracks.length; i++) { for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { if (scene.soundTracks[i].soundCollection[j].isPaused) { scene.soundTracks[i].soundCollection[j].play(); } } } } }; /** * Switch audio to headphone output. */ AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () { var scene = this.scene; this._headphone = true; scene.mainSoundTrack.switchPanningModelToHRTF(); if (scene.soundTracks) { for (var i = 0; i < scene.soundTracks.length; i++) { scene.soundTracks[i].switchPanningModelToHRTF(); } } }; /** * Switch audio to normal speakers. */ AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () { var scene = this.scene; this._headphone = false; scene.mainSoundTrack.switchPanningModelToEqualPower(); if (scene.soundTracks) { for (var i = 0; i < scene.soundTracks.length; i++) { scene.soundTracks[i].switchPanningModelToEqualPower(); } } }; AudioSceneComponent.prototype._afterRender = function () { var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_8__["PrecisionDate"].Now; if (this._lastCheck && now - this._lastCheck < this.audioPositioningRefreshRate) { return; } this._lastCheck = now; var scene = this.scene; if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) { return; } var audioEngine = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].audioEngine; if (audioEngine.audioContext) { // A custom listener position provider was set // Use the users provided position instead of camera's if (this._audioListenerPositionProvider) { var position = this._audioListenerPositionProvider(); // Make sure all coordinates were provided position.x = position.x || 0; position.y = position.y || 0; position.z = position.z || 0; // Set the listener position audioEngine.audioContext.listener.setPosition(position.x, position.y, position.z); } else { var listeningCamera; if (scene.activeCameras.length > 0) { listeningCamera = scene.activeCameras[0]; } else { listeningCamera = scene.activeCamera; } // Check if there is a listening camera if (listeningCamera) { // Set the listener position to the listening camera global position if (!this._cachedCameraPosition.equals(listeningCamera.globalPosition)) { this._cachedCameraPosition.copyFrom(listeningCamera.globalPosition); audioEngine.audioContext.listener.setPosition(listeningCamera.globalPosition.x, listeningCamera.globalPosition.y, listeningCamera.globalPosition.z); } // for VR cameras if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) { listeningCamera = listeningCamera.rigCameras[0]; } var mat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Invert(listeningCamera.getViewMatrix()); var cameraDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormal(scene.useRightHandedSystem ? AudioSceneComponent._CameraDirectionRH : AudioSceneComponent._CameraDirectionLH, mat); cameraDirection.normalize(); // To avoid some errors on GearVR if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) { if (!this._cachedCameraDirection.equals(cameraDirection)) { this._cachedCameraDirection.copyFrom(cameraDirection); audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0); } } } // Otherwise set the listener position to 0, 0 ,0 else { // Set the listener position audioEngine.audioContext.listener.setPosition(0, 0, 0); } } var i; for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) { var sound = scene.mainSoundTrack.soundCollection[i]; if (sound.useCustomAttenuation) { sound.updateDistanceFromListener(); } } if (scene.soundTracks) { for (i = 0; i < scene.soundTracks.length; i++) { for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) { sound = scene.soundTracks[i].soundCollection[j]; if (sound.useCustomAttenuation) { sound.updateDistanceFromListener(); } } } } } }; AudioSceneComponent._CameraDirectionLH = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, -1); AudioSceneComponent._CameraDirectionRH = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1); return AudioSceneComponent; }()); _sound__WEBPACK_IMPORTED_MODULE_0__["Sound"]._SceneComponentInitialization = function (scene) { var compo = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_AUDIO); if (!compo) { compo = new AudioSceneComponent(scene); scene._addComponent(compo); } }; /***/ }), /***/ "./Audio/index.ts": /*!************************!*\ !*** ./Audio/index.ts ***! \************************/ /*! exports provided: Analyser, AudioEngine, AudioSceneComponent, Sound, SoundTrack, WeightedSound */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _analyser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./analyser */ "./Audio/analyser.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return _analyser__WEBPACK_IMPORTED_MODULE_0__["Analyser"]; }); /* harmony import */ var _audioEngine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./audioEngine */ "./Audio/audioEngine.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return _audioEngine__WEBPACK_IMPORTED_MODULE_1__["AudioEngine"]; }); /* harmony import */ var _audioSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./audioSceneComponent */ "./Audio/audioSceneComponent.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return _audioSceneComponent__WEBPACK_IMPORTED_MODULE_2__["AudioSceneComponent"]; }); /* harmony import */ var _sound__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sound */ "./Audio/sound.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _sound__WEBPACK_IMPORTED_MODULE_3__["Sound"]; }); /* harmony import */ var _soundTrack__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./soundTrack */ "./Audio/soundTrack.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return _soundTrack__WEBPACK_IMPORTED_MODULE_4__["SoundTrack"]; }); /* harmony import */ var _weightedsound__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./weightedsound */ "./Audio/weightedsound.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return _weightedsound__WEBPACK_IMPORTED_MODULE_5__["WeightedSound"]; }); /***/ }), /***/ "./Audio/sound.ts": /*!************************!*\ !*** ./Audio/sound.ts ***! \************************/ /*! exports provided: Sound */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return Sound; }); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts"); /** * Defines a sound that can be played in the application. * The sound can either be an ambient track or a simple sound played in reaction to a user action. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music */ var Sound = /** @class */ (function () { /** * Create a sound and attach it to a scene * @param name Name of your sound * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams * @param scene defines the scene the sound belongs to * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming */ function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) { var _this = this; if (readyToPlayCallback === void 0) { readyToPlayCallback = null; } var _a, _b, _c, _d; /** * Does the sound autoplay once loaded. */ this.autoplay = false; /** * Does the sound loop after it finishes playing once. */ this.loop = false; /** * Does the sound use a custom attenuation curve to simulate the falloff * happening when the source gets further away from the camera. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function */ this.useCustomAttenuation = false; /** * Is this sound currently played. */ this.isPlaying = false; /** * Is this sound currently paused. */ this.isPaused = false; /** * Does this sound enables spatial sound. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.spatialSound = false; /** * Define the reference distance the sound should be heard perfectly. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.refDistance = 1; /** * Define the roll off factor of spatial sounds. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.rolloffFactor = 1; /** * Define the max distance the sound should be heard (intensity just became 0 at this point). * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.maxDistance = 100; /** * Define the distance attenuation model the sound will follow. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ this.distanceModel = "linear"; /** * Gets or sets an object used to store user defined information for the sound. */ this.metadata = null; /** * Observable event when the current playing sound finishes. */ this.onEndedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this._panningModel = "equalpower"; this._playbackRate = 1; this._streaming = false; this._startTime = 0; this._startOffset = 0; this._position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(); /** @hidden */ this._positionInEmitterSpace = false; this._localDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 0, 0); this._volume = 1; this._isReadyToPlay = false; this._isDirectional = false; // Used if you'd like to create a directional sound. // If not set, the sound will be omnidirectional this._coneInnerAngle = 360; this._coneOuterAngle = 360; this._coneOuterGain = 0; this._isOutputConnected = false; this._urlType = "Unknown"; this.name = name; this._scene = scene; Sound._SceneComponentInitialization(scene); this._readyToPlayCallback = readyToPlayCallback; // Default custom attenuation function is a linear attenuation this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) { if (currentDistance < maxDistance) { return currentVolume * (1 - currentDistance / maxDistance); } else { return 0; } }; if (options) { this.autoplay = options.autoplay || false; this.loop = options.loop || false; // if volume === 0, we need another way to check this option if (options.volume !== undefined) { this._volume = options.volume; } this.spatialSound = (_a = options.spatialSound) !== null && _a !== void 0 ? _a : false; this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : 100; this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : false; this.rolloffFactor = options.rolloffFactor || 1; this.refDistance = options.refDistance || 1; this.distanceModel = options.distanceModel || "linear"; this._playbackRate = options.playbackRate || 1; this._streaming = (_d = options.streaming) !== null && _d !== void 0 ? _d : false; this._length = options.length; this._offset = options.offset; } if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { this._soundGain = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createGain(); this._soundGain.gain.value = this._volume; this._inputAudioNode = this._soundGain; this._outputAudioNode = this._soundGain; if (this.spatialSound) { this._createSpatialParameters(); } this._scene.mainSoundTrack.AddSound(this); var validParameter = true; // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound if (urlOrArrayBuffer) { try { if (typeof urlOrArrayBuffer === "string") { this._urlType = "String"; } else if (urlOrArrayBuffer instanceof ArrayBuffer) { this._urlType = "ArrayBuffer"; } else if (urlOrArrayBuffer instanceof MediaStream) { this._urlType = "MediaStream"; } else if (Array.isArray(urlOrArrayBuffer)) { this._urlType = "Array"; } var urls = []; var codecSupportedFound = false; switch (this._urlType) { case "MediaStream": this._streaming = true; this._isReadyToPlay = true; this._streamingSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer); if (this.autoplay) { this.play(0, this._offset, this._length); } if (this._readyToPlayCallback) { this._readyToPlayCallback(); } break; case "ArrayBuffer": if (urlOrArrayBuffer.byteLength > 0) { codecSupportedFound = true; this._soundLoaded(urlOrArrayBuffer); } break; case "String": urls.push(urlOrArrayBuffer); case "Array": if (urls.length === 0) { urls = urlOrArrayBuffer; } // If we found a supported format, we load it immediately and stop the loop for (var i = 0; i < urls.length; i++) { var url = urls[i]; codecSupportedFound = (options && options.skipCodecCheck) || (url.indexOf(".mp3", url.length - 4) !== -1 && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.isMP3supported) || (url.indexOf(".ogg", url.length - 4) !== -1 && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.isOGGsupported) || url.indexOf(".wav", url.length - 4) !== -1 || url.indexOf("blob:") !== -1; if (codecSupportedFound) { // Loading sound using XHR2 if (!this._streaming) { this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true, function (exception) { if (exception) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("XHR " + exception.status + " error on: " + url + "."); } _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Sound creation aborted."); _this._scene.mainSoundTrack.RemoveSound(_this); }); } // Streaming sound using HTML5 Audio tag else { this._htmlAudioElement = new Audio(url); this._htmlAudioElement.controls = false; this._htmlAudioElement.loop = this.loop; _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].SetCorsBehavior(url, this._htmlAudioElement); this._htmlAudioElement.preload = "auto"; this._htmlAudioElement.addEventListener("canplaythrough", function () { _this._isReadyToPlay = true; if (_this.autoplay) { _this.play(0, _this._offset, _this._length); } if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }); document.body.appendChild(this._htmlAudioElement); this._htmlAudioElement.load(); } break; } } break; default: validParameter = false; break; } if (!validParameter) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound."); } else { if (!codecSupportedFound) { this._isReadyToPlay = true; // Simulating a ready to play event to avoid breaking code path if (this._readyToPlayCallback) { window.setTimeout(function () { if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, 1000); } } } } catch (ex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Unexpected error. Sound creation aborted."); this._scene.mainSoundTrack.RemoveSound(this); } } } else { // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers this._scene.mainSoundTrack.AddSound(this); if (!_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.WarnedWebAudioUnsupported) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Web Audio is not supported by your browser."); _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.WarnedWebAudioUnsupported = true; } // Simulating a ready to play event to avoid breaking code for non web audio browsers if (this._readyToPlayCallback) { window.setTimeout(function () { if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, 1000); } } } /** * Release the sound and its associated resources */ Sound.prototype.dispose = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { if (this.isPlaying) { this.stop(); } this._isReadyToPlay = false; if (this.soundTrackId === -1) { this._scene.mainSoundTrack.RemoveSound(this); } else if (this._scene.soundTracks) { this._scene.soundTracks[this.soundTrackId].RemoveSound(this); } if (this._soundGain) { this._soundGain.disconnect(); this._soundGain = null; } if (this._soundPanner) { this._soundPanner.disconnect(); this._soundPanner = null; } if (this._soundSource) { this._soundSource.disconnect(); this._soundSource = null; } this._audioBuffer = null; if (this._htmlAudioElement) { this._htmlAudioElement.pause(); this._htmlAudioElement.src = ""; document.body.removeChild(this._htmlAudioElement); } if (this._streamingSource) { this._streamingSource.disconnect(); } if (this._connectedTransformNode && this._registerFunc) { this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._connectedTransformNode = null; } } }; /** * Gets if the sounds is ready to be played or not. * @returns true if ready, otherwise false */ Sound.prototype.isReady = function () { return this._isReadyToPlay; }; Sound.prototype._soundLoaded = function (audioData) { var _this = this; if (!_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { return; } _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.decodeAudioData(audioData, function (buffer) { _this._audioBuffer = buffer; _this._isReadyToPlay = true; if (_this.autoplay) { _this.play(0, _this._offset, _this._length); } if (_this._readyToPlayCallback) { _this._readyToPlayCallback(); } }, function (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); }); }; /** * Sets the data of the sound from an audiobuffer * @param audioBuffer The audioBuffer containing the data */ Sound.prototype.setAudioBuffer = function (audioBuffer) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { this._audioBuffer = audioBuffer; this._isReadyToPlay = true; } }; /** * Updates the current sounds options such as maxdistance, loop... * @param options A JSON object containing values named as the object properties */ Sound.prototype.updateOptions = function (options) { var _a, _b, _c, _d, _e, _f, _g, _h, _j; if (options) { this.loop = (_a = options.loop) !== null && _a !== void 0 ? _a : this.loop; this.maxDistance = (_b = options.maxDistance) !== null && _b !== void 0 ? _b : this.maxDistance; this.useCustomAttenuation = (_c = options.useCustomAttenuation) !== null && _c !== void 0 ? _c : this.useCustomAttenuation; this.rolloffFactor = (_d = options.rolloffFactor) !== null && _d !== void 0 ? _d : this.rolloffFactor; this.refDistance = (_e = options.refDistance) !== null && _e !== void 0 ? _e : this.refDistance; this.distanceModel = (_f = options.distanceModel) !== null && _f !== void 0 ? _f : this.distanceModel; this._playbackRate = (_g = options.playbackRate) !== null && _g !== void 0 ? _g : this._playbackRate; this._length = (_h = options.length) !== null && _h !== void 0 ? _h : undefined; this._offset = (_j = options.offset) !== null && _j !== void 0 ? _j : undefined; this._updateSpatialParameters(); if (this.isPlaying) { if (this._streaming && this._htmlAudioElement) { this._htmlAudioElement.playbackRate = this._playbackRate; if (this._htmlAudioElement.loop !== this.loop) { this._htmlAudioElement.loop = this.loop; } } else { if (this._soundSource) { this._soundSource.playbackRate.value = this._playbackRate; if (this._soundSource.loop !== this.loop) { this._soundSource.loop = this.loop; } if (this._offset !== undefined && this._soundSource.loopStart !== this._offset) { this._soundSource.loopStart = this._offset; } if (this._length !== undefined && this._length !== this._soundSource.loopEnd) { this._soundSource.loopEnd = (this._offset | 0) + this._length; } } } } } }; Sound.prototype._createSpatialParameters = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { if (this._scene.headphone) { this._panningModel = "HRTF"; } this._soundPanner = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createPanner(); this._updateSpatialParameters(); this._soundPanner.connect(this._outputAudioNode); this._inputAudioNode = this._soundPanner; } }; Sound.prototype._updateSpatialParameters = function () { if (this.spatialSound && this._soundPanner) { if (this.useCustomAttenuation) { // Tricks to disable in a way embedded Web Audio attenuation this._soundPanner.distanceModel = "linear"; this._soundPanner.maxDistance = Number.MAX_VALUE; this._soundPanner.refDistance = 1; this._soundPanner.rolloffFactor = 1; this._soundPanner.panningModel = this._panningModel; } else { this._soundPanner.distanceModel = this.distanceModel; this._soundPanner.maxDistance = this.maxDistance; this._soundPanner.refDistance = this.refDistance; this._soundPanner.rolloffFactor = this.rolloffFactor; this._soundPanner.panningModel = this._panningModel; } } }; /** * Switch the panning model to HRTF: * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ Sound.prototype.switchPanningModelToHRTF = function () { this._panningModel = "HRTF"; this._switchPanningModel(); }; /** * Switch the panning model to Equal Power: * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ Sound.prototype.switchPanningModelToEqualPower = function () { this._panningModel = "equalpower"; this._switchPanningModel(); }; Sound.prototype._switchPanningModel = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.panningModel = this._panningModel; } }; /** * Connect this sound to a sound track audio node like gain... * @param soundTrackAudioNode the sound track audio node to connect to */ Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio) { if (this._isOutputConnected) { this._outputAudioNode.disconnect(); } this._outputAudioNode.connect(soundTrackAudioNode); this._isOutputConnected = true; } }; /** * Transform this sound into a directional source * @param coneInnerAngle Size of the inner cone in degree * @param coneOuterAngle Size of the outer cone in degree * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0) */ Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) { if (coneOuterAngle < coneInnerAngle) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = coneInnerAngle; this._coneOuterAngle = coneOuterAngle; this._coneOuterGain = coneOuterGain; this._isDirectional = true; if (this.isPlaying && this.loop) { this.stop(); this.play(0, this._offset, this._length); } }; Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", { /** * Gets or sets the inner angle for the directional cone. */ get: function () { return this._coneInnerAngle; }, /** * Gets or sets the inner angle for the directional cone. */ set: function (value) { if (value != this._coneInnerAngle) { if (this._coneOuterAngle < value) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = value; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.coneInnerAngle = this._coneInnerAngle; } } }, enumerable: false, configurable: true }); Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", { /** * Gets or sets the outer angle for the directional cone. */ get: function () { return this._coneOuterAngle; }, /** * Gets or sets the outer angle for the directional cone. */ set: function (value) { if (value != this._coneOuterAngle) { if (value < this._coneInnerAngle) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneOuterAngle = value; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) { this._soundPanner.coneOuterAngle = this._coneOuterAngle; } } }, enumerable: false, configurable: true }); /** * Sets the position of the emitter if spatial sound is enabled * @param newPosition Defines the new posisiton */ Sound.prototype.setPosition = function (newPosition) { this._position = newPosition; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); } }; /** * Sets the local direction of the emitter if spatial sound is enabled * @param newLocalDirection Defines the new local direction */ Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) { this._localDirection = newLocalDirection; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._connectedTransformNode && this.isPlaying) { this._updateDirection(); } }; Sound.prototype._updateDirection = function () { if (!this._connectedTransformNode || !this._soundPanner) { return; } var mat = this._connectedTransformNode.getWorldMatrix(); var direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormal(this._localDirection, mat); direction.normalize(); this._soundPanner.setOrientation(direction.x, direction.y, direction.z); }; /** @hidden */ Sound.prototype.updateDistanceFromListener = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._connectedTransformNode && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) { var distance = this._connectedTransformNode.getDistanceToCamera(this._scene.activeCamera); this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor); } }; /** * Sets a new custom attenuation function for the sound. * @param callback Defines the function used for the attenuation * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function */ Sound.prototype.setAttenuationFunction = function (callback) { this._customAttenuationFunction = callback; }; /** * Play the sound * @param time (optional) Start the sound after X seconds. Start immediately (0) by default. * @param offset (optional) Start the sound at a specific time in seconds * @param length (optional) Sound duration (in seconds) */ Sound.prototype.play = function (time, offset, length) { var _this = this; if (this._isReadyToPlay && this._scene.audioEnabled && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { try { if (this._startOffset < 0) { time = -this._startOffset; this._startOffset = 0; } var startTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; if (!this._soundSource || !this._streamingSource) { if (this.spatialSound && this._soundPanner) { if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) { this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z); } if (this._isDirectional) { this._soundPanner.coneInnerAngle = this._coneInnerAngle; this._soundPanner.coneOuterAngle = this._coneOuterAngle; this._soundPanner.coneOuterGain = this._coneOuterGain; if (this._connectedTransformNode) { this._updateDirection(); } else { this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z); } } } } if (this._streaming) { if (!this._streamingSource) { this._streamingSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement); this._htmlAudioElement.onended = function () { _this._onended(); }; this._htmlAudioElement.playbackRate = this._playbackRate; } this._streamingSource.disconnect(); this._streamingSource.connect(this._inputAudioNode); if (this._htmlAudioElement) { // required to manage properly the new suspended default state of Chrome // When the option 'streaming: true' is used, we need first to wait for // the audio engine to be unlocked by a user gesture before trying to play // an HTML Audio elememt var tryToPlay = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.unlocked) { var playPromise = _this._htmlAudioElement.play(); // In browsers that don’t yet support this functionality, // playPromise won’t be defined. if (playPromise !== undefined) { playPromise.catch(function (error) { // Automatic playback failed. // Waiting for the audio engine to be unlocked by user click on unmute _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.lock(); if (_this.loop || _this.autoplay) { _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); } }); } } else { if (_this.loop || _this.autoplay) { _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); } } }; tryToPlay(); } } else { var tryToPlay = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { length = length || _this._length; offset = offset || _this._offset; if (_this._soundSource) { var oldSource_1 = _this._soundSource; oldSource_1.onended = function () { oldSource_1.disconnect(); }; } _this._soundSource = _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.createBufferSource(); _this._soundSource.buffer = _this._audioBuffer; _this._soundSource.connect(_this._inputAudioNode); _this._soundSource.loop = _this.loop; if (offset !== undefined) { _this._soundSource.loopStart = offset; } if (length !== undefined) { _this._soundSource.loopEnd = (offset | 0) + length; } _this._soundSource.playbackRate.value = _this._playbackRate; _this._soundSource.onended = function () { _this._onended(); }; startTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; var actualOffset = _this.isPaused ? _this._startOffset % _this._soundSource.buffer.duration : offset ? offset : 0; _this._soundSource.start(startTime, actualOffset, _this.loop ? undefined : length); } }; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.state === "suspended") { // Wait a bit for FF as context seems late to be ready. setTimeout(function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.state === "suspended") { // Automatic playback failed. // Waiting for the audio engine to be unlocked by user click on unmute _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.lock(); if (_this.loop || _this.autoplay) { _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); }); } } else { tryToPlay(); } }, 500); } else { tryToPlay(); } } this._startTime = startTime; this.isPlaying = true; this.isPaused = false; } catch (ex) { _Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("Error while trying to play audio: " + this.name + ", " + ex.message); } } }; Sound.prototype._onended = function () { this.isPlaying = false; if (this.onended) { this.onended(); } this.onEndedObservable.notifyObservers(this); }; /** * Stop the sound * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default. */ Sound.prototype.stop = function (time) { var _this = this; if (this.isPlaying) { if (this._streaming) { if (this._htmlAudioElement) { this._htmlAudioElement.pause(); // Test needed for Firefox or it will generate an Invalid State Error if (this._htmlAudioElement.currentTime > 0) { this._htmlAudioElement.currentTime = 0; } } else { this._streamingSource.disconnect(); } this.isPlaying = false; } else if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext && this._soundSource) { var stopTime = time ? _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time : _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime; this._soundSource.stop(stopTime); this._soundSource.onended = function () { _this.isPlaying = false; }; if (!this.isPaused) { this._startOffset = 0; } } } }; /** * Put the sound in pause */ Sound.prototype.pause = function () { if (this.isPlaying) { this.isPaused = true; if (this._streaming) { if (this._htmlAudioElement) { this._htmlAudioElement.pause(); } else { this._streamingSource.disconnect(); } } else if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { this.stop(0); this._startOffset += _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime - this._startTime; } } }; /** * Sets a dedicated volume for this sounds * @param newVolume Define the new volume of the sound * @param time Define time for gradual change to new volume */ Sound.prototype.setVolume = function (newVolume, time) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._soundGain) { if (time && _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext) { this._soundGain.gain.cancelScheduledValues(_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime); this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime); this._soundGain.gain.linearRampToValueAtTime(newVolume, _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.audioContext.currentTime + time); } else { this._soundGain.gain.value = newVolume; } } this._volume = newVolume; }; /** * Set the sound play back rate * @param newPlaybackRate Define the playback rate the sound should be played at */ Sound.prototype.setPlaybackRate = function (newPlaybackRate) { this._playbackRate = newPlaybackRate; if (this.isPlaying) { if (this._streaming && this._htmlAudioElement) { this._htmlAudioElement.playbackRate = this._playbackRate; } else if (this._soundSource) { this._soundSource.playbackRate.value = this._playbackRate; } } }; /** * Gets the volume of the sound. * @returns the volume of the sound */ Sound.prototype.getVolume = function () { return this._volume; }; /** * Attach the sound to a dedicated mesh * @param transformNode The transform node to connect the sound with * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh */ Sound.prototype.attachToMesh = function (transformNode) { var _this = this; if (this._connectedTransformNode && this._registerFunc) { this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._registerFunc = null; } this._connectedTransformNode = transformNode; if (!this.spatialSound) { this.spatialSound = true; this._createSpatialParameters(); if (this.isPlaying && this.loop) { this.stop(); this.play(0, this._offset, this._length); } } this._onRegisterAfterWorldMatrixUpdate(this._connectedTransformNode); this._registerFunc = function (transformNode) { return _this._onRegisterAfterWorldMatrixUpdate(transformNode); }; this._connectedTransformNode.registerAfterWorldMatrixUpdate(this._registerFunc); }; /** * Detach the sound from the previously attached mesh * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh */ Sound.prototype.detachFromMesh = function () { if (this._connectedTransformNode && this._registerFunc) { this._connectedTransformNode.unregisterAfterWorldMatrixUpdate(this._registerFunc); this._registerFunc = null; this._connectedTransformNode = null; } }; Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) { if (this._positionInEmitterSpace) { node.worldMatrixFromCache.invertToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Matrix[0]); this.setPosition(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Matrix[0].getTranslation()); } else { if (!node.getBoundingInfo) { this.setPosition(node.absolutePosition); } else { var mesh = node; var boundingInfo = mesh.getBoundingInfo(); this.setPosition(boundingInfo.boundingSphere.centerWorld); } } if (_Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) { this._updateDirection(); } }; /** * Clone the current sound in the scene. * @returns the new sound clone */ Sound.prototype.clone = function () { var _this = this; if (!this._streaming) { var setBufferAndRun = function () { if (_this._isReadyToPlay) { clonedSound._audioBuffer = _this.getAudioBuffer(); clonedSound._isReadyToPlay = true; if (clonedSound.autoplay) { clonedSound.play(0, _this._offset, _this._length); } } else { window.setTimeout(setBufferAndRun, 300); } }; var currentOptions = { autoplay: this.autoplay, loop: this.loop, volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor, refDistance: this.refDistance, distanceModel: this.distanceModel, }; var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions); if (this.useCustomAttenuation) { clonedSound.setAttenuationFunction(this._customAttenuationFunction); } clonedSound.setPosition(this._position); clonedSound.setPlaybackRate(this._playbackRate); setBufferAndRun(); return clonedSound; } // Can't clone a streaming sound else { return null; } }; /** * Gets the current underlying audio buffer containing the data * @returns the audio buffer */ Sound.prototype.getAudioBuffer = function () { return this._audioBuffer; }; /** * Gets the WebAudio AudioBufferSourceNode, lets you keep track of and stop instances of this Sound. * @returns the source node */ Sound.prototype.getSoundSource = function () { return this._soundSource; }; /** * Gets the WebAudio GainNode, gives you precise control over the gain of instances of this Sound. * @returns the gain node */ Sound.prototype.getSoundGain = function () { return this._soundGain; }; /** * Serializes the Sound in a JSON representation * @returns the JSON representation of the sound */ Sound.prototype.serialize = function () { var serializationObject = { name: this.name, url: this.name, autoplay: this.autoplay, loop: this.loop, volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance, rolloffFactor: this.rolloffFactor, refDistance: this.refDistance, distanceModel: this.distanceModel, playbackRate: this._playbackRate, panningModel: this._panningModel, soundTrackId: this.soundTrackId, metadata: this.metadata, }; if (this.spatialSound) { if (this._connectedTransformNode) { serializationObject.connectedMeshId = this._connectedTransformNode.id; } serializationObject.position = this._position.asArray(); serializationObject.refDistance = this.refDistance; serializationObject.distanceModel = this.distanceModel; serializationObject.isDirectional = this._isDirectional; serializationObject.localDirectionToMesh = this._localDirection.asArray(); serializationObject.coneInnerAngle = this._coneInnerAngle; serializationObject.coneOuterAngle = this._coneOuterAngle; serializationObject.coneOuterGain = this._coneOuterGain; } return serializationObject; }; /** * Parse a JSON representation of a sound to innstantiate in a given scene * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method) * @param scene Define the scene the new parsed sound should be created in * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies * @param sourceSound Define a cound place holder if do not need to instantiate a new one * @returns the newly parsed sound */ Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) { var soundName = parsedSound.name; var soundUrl; if (parsedSound.url) { soundUrl = rootUrl + parsedSound.url; } else { soundUrl = rootUrl + soundName; } var options = { autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume, spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance, rolloffFactor: parsedSound.rolloffFactor, refDistance: parsedSound.refDistance, distanceModel: parsedSound.distanceModel, playbackRate: parsedSound.playbackRate, }; var newSound; if (!sourceSound) { newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options); scene._addPendingData(newSound); } else { var setBufferAndRun = function () { if (sourceSound._isReadyToPlay) { newSound._audioBuffer = sourceSound.getAudioBuffer(); newSound._isReadyToPlay = true; if (newSound.autoplay) { newSound.play(0, newSound._offset, newSound._length); } } else { window.setTimeout(setBufferAndRun, 300); } }; newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options); setBufferAndRun(); } if (parsedSound.position) { var soundPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSound.position); newSound.setPosition(soundPosition); } if (parsedSound.isDirectional) { newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0); if (parsedSound.localDirectionToMesh) { var localDirectionToMesh = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSound.localDirectionToMesh); newSound.setLocalDirectionToMesh(localDirectionToMesh); } } if (parsedSound.connectedMeshId) { var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId); if (connectedMesh) { newSound.attachToMesh(connectedMesh); } } if (parsedSound.metadata) { newSound.metadata = parsedSound.metadata; } return newSound; }; /** @hidden */ Sound._SceneComponentInitialization = function (_) { throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_5__["_DevTools"].WarnImport("AudioSceneComponent"); }; return Sound; }()); /***/ }), /***/ "./Audio/soundTrack.ts": /*!*****************************!*\ !*** ./Audio/soundTrack.ts ***! \*****************************/ /*! exports provided: SoundTrack */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return SoundTrack; }); /* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts"); /** * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds. * It will be also used in a future release to apply effects on a specific track. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks */ var SoundTrack = /** @class */ (function () { /** * Creates a new sound track. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks * @param scene Define the scene the sound track belongs to * @param options */ function SoundTrack(scene, options) { if (options === void 0) { options = {}; } /** * The unique identifier of the sound track in the scene. */ this.id = -1; this._isInitialized = false; this._scene = scene; this.soundCollection = new Array(); this._options = options; if (!this._options.mainTrack && this._scene.soundTracks) { this._scene.soundTracks.push(this); this.id = this._scene.soundTracks.length - 1; } } SoundTrack.prototype._initializeSoundTrackAudioGraph = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.audioContext) { this._outputAudioNode = _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.audioContext.createGain(); this._outputAudioNode.connect(_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.masterGain); if (this._options) { if (this._options.volume) { this._outputAudioNode.gain.value = this._options.volume; } } this._isInitialized = true; } }; /** * Release the sound track and its associated resources */ SoundTrack.prototype.dispose = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine && _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } while (this.soundCollection.length) { this.soundCollection[0].dispose(); } if (this._outputAudioNode) { this._outputAudioNode.disconnect(); } this._outputAudioNode = null; } }; /** * Adds a sound to this sound track * @param sound define the cound to add * @ignoreNaming */ SoundTrack.prototype.AddSound = function (sound) { if (!this._isInitialized) { this._initializeSoundTrackAudioGraph(); } if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { sound.connectToSoundTrackAudioNode(this._outputAudioNode); } if (sound.soundTrackId) { if (sound.soundTrackId === -1) { this._scene.mainSoundTrack.RemoveSound(sound); } else if (this._scene.soundTracks) { this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound); } } this.soundCollection.push(sound); sound.soundTrackId = this.id; }; /** * Removes a sound to this sound track * @param sound define the cound to remove * @ignoreNaming */ SoundTrack.prototype.RemoveSound = function (sound) { var index = this.soundCollection.indexOf(sound); if (index !== -1) { this.soundCollection.splice(index, 1); } }; /** * Set a global volume for the full sound track. * @param newVolume Define the new volume of the sound track */ SoundTrack.prototype.setVolume = function (newVolume) { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { this._outputAudioNode.gain.value = newVolume; } }; /** * Switch the panning model to HRTF: * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ SoundTrack.prototype.switchPanningModelToHRTF = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { for (var i = 0; i < this.soundCollection.length; i++) { this.soundCollection[i].switchPanningModelToHRTF(); } } }; /** * Switch the panning model to Equal Power: * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value. * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound */ SoundTrack.prototype.switchPanningModelToEqualPower = function () { if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio) { for (var i = 0; i < this.soundCollection.length; i++) { this.soundCollection[i].switchPanningModelToEqualPower(); } } }; /** * Connect the sound track to an audio analyser allowing some amazing * synchornization between the sounds/music and your visualization (VuMeter for instance). * @see https://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser * @param analyser The analyser to connect to the engine */ SoundTrack.prototype.connectToAnalyser = function (analyser) { if (this._connectedAnalyser) { this._connectedAnalyser.stopDebugCanvas(); } this._connectedAnalyser = analyser; if (_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.canUseWebAudio && this._outputAudioNode) { this._outputAudioNode.disconnect(); this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].audioEngine.masterGain); } }; return SoundTrack; }()); /***/ }), /***/ "./Audio/weightedsound.ts": /*!********************************!*\ !*** ./Audio/weightedsound.ts ***! \********************************/ /*! exports provided: WeightedSound */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return WeightedSound; }); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /** * Wraps one or more Sound objects and selects one with random weight for playback. */ var WeightedSound = /** @class */ (function () { /** * Creates a new WeightedSound from the list of sounds given. * @param loop When true a Sound will be selected and played when the current playing Sound completes. * @param sounds Array of Sounds that will be selected from. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1 */ function WeightedSound(loop, sounds, weights) { var _this = this; /** When true a Sound will be selected and played when the current playing Sound completes. */ this.loop = false; this._coneInnerAngle = 360; this._coneOuterAngle = 360; this._volume = 1; /** A Sound is currently playing. */ this.isPlaying = false; /** A Sound is currently paused. */ this.isPaused = false; this._sounds = []; this._weights = []; if (sounds.length !== weights.length) { throw new Error('Sounds length does not equal weights length'); } this.loop = loop; this._weights = weights; // Normalize the weights var weightSum = 0; for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) { var weight = weights_1[_i]; weightSum += weight; } var invWeightSum = weightSum > 0 ? 1 / weightSum : 0; for (var i = 0; i < this._weights.length; i++) { this._weights[i] *= invWeightSum; } this._sounds = sounds; for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) { var sound = _b[_a]; sound.onEndedObservable.add(function () { _this._onended(); }); } } Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", { /** * The size of cone in degrees for a directional sound in which there will be no attenuation. */ get: function () { return this._coneInnerAngle; }, /** * The size of cone in degress for a directional sound in which there will be no attenuation. */ set: function (value) { if (value !== this._coneInnerAngle) { if (this._coneOuterAngle < value) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneInnerAngle = value; for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { var sound = _a[_i]; sound.directionalConeInnerAngle = value; } } }, enumerable: false, configurable: true }); Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", { /** * Size of cone in degrees for a directional sound outside of which there will be no sound. * Listener angles between innerAngle and outerAngle will falloff linearly. */ get: function () { return this._coneOuterAngle; }, /** * Size of cone in degrees for a directional sound outside of which there will be no sound. * Listener angles between innerAngle and outerAngle will falloff linearly. */ set: function (value) { if (value !== this._coneOuterAngle) { if (value < this._coneInnerAngle) { _Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle."); return; } this._coneOuterAngle = value; for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { var sound = _a[_i]; sound.directionalConeOuterAngle = value; } } }, enumerable: false, configurable: true }); Object.defineProperty(WeightedSound.prototype, "volume", { /** * Playback volume. */ get: function () { return this._volume; }, /** * Playback volume. */ set: function (value) { if (value !== this._volume) { for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) { var sound = _a[_i]; sound.setVolume(value); } } }, enumerable: false, configurable: true }); WeightedSound.prototype._onended = function () { if (this._currentIndex !== undefined) { this._sounds[this._currentIndex].autoplay = false; } if (this.loop && this.isPlaying) { this.play(); } else { this.isPlaying = false; } }; /** * Suspend playback */ WeightedSound.prototype.pause = function () { this.isPaused = true; if (this._currentIndex !== undefined) { this._sounds[this._currentIndex].pause(); } }; /** * Stop playback */ WeightedSound.prototype.stop = function () { this.isPlaying = false; if (this._currentIndex !== undefined) { this._sounds[this._currentIndex].stop(); } }; /** * Start playback. * @param startOffset Position the clip head at a specific time in seconds. */ WeightedSound.prototype.play = function (startOffset) { if (!this.isPaused) { this.stop(); var randomValue = Math.random(); var total = 0; for (var i = 0; i < this._weights.length; i++) { total += this._weights[i]; if (randomValue <= total) { this._currentIndex = i; break; } } } var sound = this._sounds[this._currentIndex]; if (sound.isReady()) { sound.play(0, this.isPaused ? undefined : startOffset); } else { sound.autoplay = true; } this.isPlaying = true; this.isPaused = false; }; return WeightedSound; }()); /***/ }), /***/ "./Behaviors/Cameras/autoRotationBehavior.ts": /*!***************************************************!*\ !*** ./Behaviors/Cameras/autoRotationBehavior.ts ***! \***************************************************/ /*! exports provided: AutoRotationBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return AutoRotationBehavior; }); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/precisionDate */ "./Misc/precisionDate.ts"); /** * The autoRotation behavior (AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction. * @see https://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior */ var AutoRotationBehavior = /** @class */ (function () { function AutoRotationBehavior() { this._zoomStopsAnimation = false; this._idleRotationSpeed = 0.05; this._idleRotationWaitTime = 2000; this._idleRotationSpinupTime = 2000; this._isPointerDown = false; this._lastFrameTime = null; this._lastInteractionTime = -Infinity; this._cameraRotationSpeed = 0; this._lastFrameRadius = 0; } Object.defineProperty(AutoRotationBehavior.prototype, "name", { /** * Gets the name of the behavior. */ get: function () { return "AutoRotation"; }, enumerable: false, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", { /** * Gets the flag that indicates if user zooming should stop animation. */ get: function () { return this._zoomStopsAnimation; }, /** * Sets the flag that indicates if user zooming should stop animation. */ set: function (flag) { this._zoomStopsAnimation = flag; }, enumerable: false, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", { /** * Gets the default speed at which the camera rotates around the model. */ get: function () { return this._idleRotationSpeed; }, /** * Sets the default speed at which the camera rotates around the model. */ set: function (speed) { this._idleRotationSpeed = speed; }, enumerable: false, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", { /** * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating. */ get: function () { return this._idleRotationWaitTime; }, /** * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating. */ set: function (time) { this._idleRotationWaitTime = time; }, enumerable: false, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", { /** * Gets the time (milliseconds) to take to spin up to the full idle rotation speed. */ get: function () { return this._idleRotationSpinupTime; }, /** * Sets the time (milliseconds) to take to spin up to the full idle rotation speed. */ set: function (time) { this._idleRotationSpinupTime = time; }, enumerable: false, configurable: true }); Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", { /** * Gets a value indicating if the camera is currently rotating because of this behavior */ get: function () { return Math.abs(this._cameraRotationSpeed) > 0; }, enumerable: false, configurable: true }); /** * Initializes the behavior. */ AutoRotationBehavior.prototype.init = function () { // Do notihng }; /** * Attaches the behavior to its arc rotate camera. * @param camera Defines the camera to attach the behavior to */ AutoRotationBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; var scene = this._attachedCamera.getScene(); this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN) { _this._isPointerDown = true; return; } if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP) { _this._isPointerDown = false; } }); this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { var now = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__["PrecisionDate"].Now; var dt = 0; if (_this._lastFrameTime != null) { dt = now - _this._lastFrameTime; } _this._lastFrameTime = now; // Stop the animation if there is user interaction and the animation should stop for this interaction _this._applyUserInteraction(); var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime; var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0); _this._cameraRotationSpeed = _this._idleRotationSpeed * scale; // Step camera rotation by rotation speed if (_this._attachedCamera) { _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000); } }); }; /** * Detaches the behavior from its current arc rotate camera. */ AutoRotationBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } var scene = this._attachedCamera.getScene(); if (this._onPrePointerObservableObserver) { scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); } this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); this._attachedCamera = null; }; /** * Returns true if user is scrolling. * @return true if user is scrolling. */ AutoRotationBehavior.prototype._userIsZooming = function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialRadiusOffset !== 0; }; AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () { if (!this._attachedCamera) { return false; } var zoomHasHitLimit = false; if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) { zoomHasHitLimit = true; } // Update the record of previous radius - works as an approx. indicator of hitting radius limits this._lastFrameRadius = this._attachedCamera.radius; return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming(); }; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ AutoRotationBehavior.prototype._applyUserInteraction = function () { if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) { this._lastInteractionTime = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_1__["PrecisionDate"].Now; } }; // Tools AutoRotationBehavior.prototype._userIsMoving = function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }; return AutoRotationBehavior; }()); /***/ }), /***/ "./Behaviors/Cameras/bouncingBehavior.ts": /*!***********************************************!*\ !*** ./Behaviors/Cameras/bouncingBehavior.ts ***! \***********************************************/ /*! exports provided: BouncingBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return BouncingBehavior; }); /* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); /** * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius * @see https://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior */ var BouncingBehavior = /** @class */ (function () { function BouncingBehavior() { /** * The duration of the animation, in milliseconds */ this.transitionDuration = 450; /** * Length of the distance animated by the transition when lower radius is reached */ this.lowerRadiusTransitionRange = 2; /** * Length of the distance animated by the transition when upper radius is reached */ this.upperRadiusTransitionRange = -2; this._autoTransitionRange = false; // Animations this._radiusIsAnimating = false; this._radiusBounceTransition = null; this._animatables = new Array(); } Object.defineProperty(BouncingBehavior.prototype, "name", { /** * Gets the name of the behavior. */ get: function () { return "Bouncing"; }, enumerable: false, configurable: true }); Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", { /** * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically */ get: function () { return this._autoTransitionRange; }, /** * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically * Transition ranges will be set to 5% of the bounding box diagonal in world space */ set: function (value) { var _this = this; if (this._autoTransitionRange === value) { return; } this._autoTransitionRange = value; var camera = this._attachedCamera; if (!camera) { return; } if (value) { this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (!mesh) { return; } mesh.computeWorldMatrix(true); var diagonal = mesh.getBoundingInfo().diagonalLength; _this.lowerRadiusTransitionRange = diagonal * 0.05; _this.upperRadiusTransitionRange = diagonal * 0.05; }); } else if (this._onMeshTargetChangedObserver) { camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } }, enumerable: false, configurable: true }); /** * Initializes the behavior. */ BouncingBehavior.prototype.init = function () { // Do notihng }; /** * Attaches the behavior to its arc rotate camera. * @param camera Defines the camera to attach the behavior to */ BouncingBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { if (!_this._attachedCamera) { return; } // Add the bounce animation to the lower radius limit if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) { _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange); } // Add the bounce animation to the upper radius limit if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) { _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange); } }); }; /** * Detaches the behavior from its current arc rotate camera. */ BouncingBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } if (this._onAfterCheckInputsObserver) { this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); } if (this._onMeshTargetChangedObserver) { this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } this._attachedCamera = null; }; /** * Checks if the camera radius is at the specified limit. Takes into account animation locks. * @param radiusLimit The limit to check against. * @return Bool to indicate if at limit. */ BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) { if (!this._attachedCamera) { return false; } if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) { return true; } return false; }; /** * Applies an animation to the radius of the camera, extending by the radiusDelta. * @param radiusDelta The delta by which to animate to. Can be negative. */ BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) { var _this = this; if (!this._attachedCamera) { return; } if (!this._radiusBounceTransition) { BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode); this._radiusBounceTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].CreateAnimation("radius", _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction); } // Prevent zoom until bounce has completed this._cachedWheelPrecision = this._attachedCamera.wheelPrecision; this._attachedCamera.wheelPrecision = Infinity; this._attachedCamera.inertialRadiusOffset = 0; // Animate to the radius limit this.stopAllAnimations(); this._radiusIsAnimating = true; var animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_1__["Animation"].TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }); if (animatable) { this._animatables.push(animatable); } }; /** * Removes all animation locks. Allows new animations to be added to any of the camera properties. */ BouncingBehavior.prototype._clearAnimationLocks = function () { this._radiusIsAnimating = false; if (this._attachedCamera) { this._attachedCamera.wheelPrecision = this._cachedWheelPrecision; } }; /** * Stops and removes all animations that have been applied to the camera */ BouncingBehavior.prototype.stopAllAnimations = function () { if (this._attachedCamera) { this._attachedCamera.animations = []; } while (this._animatables.length) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); this._animatables.shift(); } }; /** * The easing function used by animations */ BouncingBehavior.EasingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["BackEase"](0.3); /** * The easing mode used by animations */ BouncingBehavior.EasingMode = _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"].EASINGMODE_EASEOUT; return BouncingBehavior; }()); /***/ }), /***/ "./Behaviors/Cameras/framingBehavior.ts": /*!**********************************************!*\ !*** ./Behaviors/Cameras/framingBehavior.ts ***! \**********************************************/ /*! exports provided: FramingBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return FramingBehavior; }); /* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/precisionDate */ "./Misc/precisionDate.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); /** * The framing behavior (FramingBehavior) is designed to automatically position an ArcRotateCamera when its target is set to a mesh. It is also useful if you want to prevent the camera to go under a virtual horizontal plane. * @see https://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior */ var FramingBehavior = /** @class */ (function () { function FramingBehavior() { this._mode = FramingBehavior.FitFrustumSidesMode; this._radiusScale = 1.0; this._positionScale = 0.5; this._defaultElevation = 0.3; this._elevationReturnTime = 1500; this._elevationReturnWaitTime = 1000; this._zoomStopsAnimation = false; this._framingTime = 1500; /** * Define if the behavior should automatically change the configured * camera limits and sensibilities. */ this.autoCorrectCameraLimitsAndSensibility = true; this._isPointerDown = false; this._lastInteractionTime = -Infinity; // Framing control this._animatables = new Array(); this._betaIsAnimating = false; } Object.defineProperty(FramingBehavior.prototype, "name", { /** * Gets the name of the behavior. */ get: function () { return "Framing"; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "mode", { /** * Gets current mode used by the behavior. */ get: function () { return this._mode; }, /** * Sets the current mode used by the behavior */ set: function (mode) { this._mode = mode; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "radiusScale", { /** * Gets the scale applied to the radius */ get: function () { return this._radiusScale; }, /** * Sets the scale applied to the radius (1 by default) */ set: function (radius) { this._radiusScale = radius; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "positionScale", { /** * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ get: function () { return this._positionScale; }, /** * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box. */ set: function (scale) { this._positionScale = scale; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "defaultElevation", { /** * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ get: function () { return this._defaultElevation; }, /** * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle * behaviour is triggered, in radians. */ set: function (elevation) { this._defaultElevation = elevation; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", { /** * Gets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ get: function () { return this._elevationReturnTime; }, /** * Sets the time (in milliseconds) taken to return to the default beta position. * Negative value indicates camera should not return to default. */ set: function (speed) { this._elevationReturnTime = speed; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", { /** * Gets the delay (in milliseconds) taken before the camera returns to the default beta position. */ get: function () { return this._elevationReturnWaitTime; }, /** * Sets the delay (in milliseconds) taken before the camera returns to the default beta position. */ set: function (time) { this._elevationReturnWaitTime = time; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", { /** * Gets the flag that indicates if user zooming should stop animation. */ get: function () { return this._zoomStopsAnimation; }, /** * Sets the flag that indicates if user zooming should stop animation. */ set: function (flag) { this._zoomStopsAnimation = flag; }, enumerable: false, configurable: true }); Object.defineProperty(FramingBehavior.prototype, "framingTime", { /** * Gets the transition time when framing the mesh, in milliseconds */ get: function () { return this._framingTime; }, /** * Sets the transition time when framing the mesh, in milliseconds */ set: function (time) { this._framingTime = time; }, enumerable: false, configurable: true }); /** * Initializes the behavior. */ FramingBehavior.prototype.init = function () { // Do notihng }; /** * Attaches the behavior to its arc rotate camera. * @param camera Defines the camera to attach the behavior to */ FramingBehavior.prototype.attach = function (camera) { var _this = this; this._attachedCamera = camera; var scene = this._attachedCamera.getScene(); FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode); this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) { if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) { _this._isPointerDown = true; return; } if (pointerInfoPre.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERUP) { _this._isPointerDown = false; } }); this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) { if (mesh) { _this.zoomOnMesh(mesh); } }); this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () { // Stop the animation if there is user interaction and the animation should stop for this interaction _this._applyUserInteraction(); // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it // back to the default position after a given timeout _this._maintainCameraAboveGround(); }); }; /** * Detaches the behavior from its current arc rotate camera. */ FramingBehavior.prototype.detach = function () { if (!this._attachedCamera) { return; } var scene = this._attachedCamera.getScene(); if (this._onPrePointerObservableObserver) { scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver); } if (this._onAfterCheckInputsObserver) { this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver); } if (this._onMeshTargetChangedObserver) { this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver); } this._attachedCamera = null; }; /** * Targets the given mesh and updates zoom level accordingly. * @param mesh The mesh to target. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } mesh.computeWorldMatrix(true); var boundingBox = mesh.getBoundingInfo().boundingBox; this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the given mesh with its children and updates zoom level accordingly. * @param mesh The mesh to target. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } mesh.computeWorldMatrix(true); var boundingBox = mesh.getHierarchyBoundingVectors(true); this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the given meshes with their children and updates zoom level accordingly. * @param meshes The mesh to target. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) { if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } var min = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); var max = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); for (var i = 0; i < meshes.length; i++) { var boundingInfo = meshes[i].getHierarchyBoundingVectors(true); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CheckExtends(boundingInfo.min, min, max); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CheckExtends(boundingInfo.max, min, max); } this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd); }; /** * Targets the bounding box info defined by its extends and updates zoom level accordingly. * @param minimumWorld Determines the smaller position of the bounding box extend * @param maximumWorld Determines the bigger position of the bounding box extend * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh * @param onAnimationEnd Callback triggered at the end of the framing animation */ FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) { var _this = this; if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; } if (onAnimationEnd === void 0) { onAnimationEnd = null; } var zoomTarget; if (!this._attachedCamera) { return; } // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY var bottom = minimumWorld.y; var top = maximumWorld.y; var zoomTargetY = bottom + (top - bottom) * this._positionScale; var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5); if (focusOnOriginXZ) { zoomTarget = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, zoomTargetY, 0); } else { var centerWorld = minimumWorld.add(radiusWorld); zoomTarget = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](centerWorld.x, zoomTargetY, centerWorld.z); } if (!this._vectorTransition) { this._vectorTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].CreateAnimation("target", _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction); } this._betaIsAnimating = true; var animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime); if (animatable) { this._animatables.push(animatable); } // sets the radius and lower radius bounds // Small delta ensures camera is not always at lower zoom limit. var radius = 0; if (this._mode === FramingBehavior.FitFrustumSidesMode) { var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); if (this.autoCorrectCameraLimitsAndSensibility) { this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ; } radius = position; } else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) { radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld); if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) { this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ; } } // Set sensibilities if (this.autoCorrectCameraLimitsAndSensibility) { var extend = maximumWorld.subtract(minimumWorld).length(); this._attachedCamera.panningSensibility = 5000 / extend; this._attachedCamera.wheelPrecision = 100 / radius; } // transition to new radius if (!this._radiusTransition) { this._radiusTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].CreateAnimation("radius", _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); } animatable = _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () { _this.stopAllAnimations(); if (onAnimationEnd) { onAnimationEnd(); } if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) { _this._attachedCamera.storeState(); } }); if (animatable) { this._animatables.push(animatable); } }; /** * Calculates the lowest radius for the camera based on the bounding box of the mesh. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary * frustum width. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order * to fully enclose the mesh in the viewing frustum. */ FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) { var size = maximumWorld.subtract(minimumWorld); var boxVectorGlobalDiagonal = size.length(); var frustumSlope = this._getFrustumSlope(); // Formula for setting distance // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene) var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5; // Horizon distance var radius = radiusWithoutFraming * this._radiusScale; var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x)); var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y)); var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum); var camera = this._attachedCamera; if (!camera) { return 0; } if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) { // Don't exceed the requested limit distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance; } // Don't exceed the upper radius limit if (camera.upperRadiusLimit) { distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance; } return distance; }; /** * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera * is automatically returned to its default position (expected to be above ground plane). */ FramingBehavior.prototype._maintainCameraAboveGround = function () { var _this = this; if (this._elevationReturnTime < 0) { return; } var timeSinceInteraction = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_2__["PrecisionDate"].Now - this._lastInteractionTime; var defaultBeta = Math.PI * 0.5 - this._defaultElevation; var limitBeta = Math.PI * 0.5; // Bring the camera back up if below the ground plane if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) { this._betaIsAnimating = true; //Transition to new position this.stopAllAnimations(); if (!this._betaTransition) { this._betaTransition = _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].CreateAnimation("beta", _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction); } var animatabe = _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () { _this._clearAnimationLocks(); _this.stopAllAnimations(); }); if (animatabe) { this._animatables.push(animatabe); } } }; /** * Returns the frustum slope based on the canvas ratio and camera FOV * @returns The frustum slope represented as a Vector2 with X and Y slopes */ FramingBehavior.prototype._getFrustumSlope = function () { // Calculate the viewport ratio // Aspect Ratio is Height/Width. var camera = this._attachedCamera; if (!camera) { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); } var engine = camera.getScene().getEngine(); var aspectRatio = engine.getAspectRatio(camera); // Camera FOV is the vertical field of view (top-bottom) in radians. // Slope of the frustum top/bottom planes in view space, relative to the forward vector. var frustumSlopeY = Math.tan(camera.fov / 2); // Slope of the frustum left/right planes in view space, relative to the forward vector. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit // along the forward vector. var frustumSlopeX = frustumSlopeY * aspectRatio; return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](frustumSlopeX, frustumSlopeY); }; /** * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties. */ FramingBehavior.prototype._clearAnimationLocks = function () { this._betaIsAnimating = false; }; /** * Applies any current user interaction to the camera. Takes into account maximum alpha rotation. */ FramingBehavior.prototype._applyUserInteraction = function () { if (this.isUserIsMoving) { this._lastInteractionTime = _Misc_precisionDate__WEBPACK_IMPORTED_MODULE_2__["PrecisionDate"].Now; this.stopAllAnimations(); this._clearAnimationLocks(); } }; /** * Stops and removes all animations that have been applied to the camera */ FramingBehavior.prototype.stopAllAnimations = function () { if (this._attachedCamera) { this._attachedCamera.animations = []; } while (this._animatables.length) { if (this._animatables[0]) { this._animatables[0].onAnimationEnd = null; this._animatables[0].stop(); } this._animatables.shift(); } }; Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", { /** * Gets a value indicating if the user is moving the camera */ get: function () { if (!this._attachedCamera) { return false; } return this._attachedCamera.inertialAlphaOffset !== 0 || this._attachedCamera.inertialBetaOffset !== 0 || this._attachedCamera.inertialRadiusOffset !== 0 || this._attachedCamera.inertialPanningX !== 0 || this._attachedCamera.inertialPanningY !== 0 || this._isPointerDown; }, enumerable: false, configurable: true }); /** * The easing function used by animations */ FramingBehavior.EasingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["ExponentialEase"](); /** * The easing mode used by animations */ FramingBehavior.EasingMode = _Animations_easing__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"].EASINGMODE_EASEINOUT; // Statics /** * The camera can move all the way towards the mesh. */ FramingBehavior.IgnoreBoundsSizeMode = 0; /** * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides */ FramingBehavior.FitFrustumSidesMode = 1; return FramingBehavior; }()); /***/ }), /***/ "./Behaviors/Cameras/index.ts": /*!************************************!*\ !*** ./Behaviors/Cameras/index.ts ***! \************************************/ /*! exports provided: AutoRotationBehavior, BouncingBehavior, FramingBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _autoRotationBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./autoRotationBehavior */ "./Behaviors/Cameras/autoRotationBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _autoRotationBehavior__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; }); /* harmony import */ var _bouncingBehavior__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bouncingBehavior */ "./Behaviors/Cameras/bouncingBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _bouncingBehavior__WEBPACK_IMPORTED_MODULE_1__["BouncingBehavior"]; }); /* harmony import */ var _framingBehavior__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./framingBehavior */ "./Behaviors/Cameras/framingBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _framingBehavior__WEBPACK_IMPORTED_MODULE_2__["FramingBehavior"]; }); /***/ }), /***/ "./Behaviors/Meshes/attachToBoxBehavior.ts": /*!*************************************************!*\ !*** ./Behaviors/Meshes/attachToBoxBehavior.ts ***! \*************************************************/ /*! exports provided: AttachToBoxBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return AttachToBoxBehavior; }); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /** * @hidden */ var FaceDirectionInfo = /** @class */ (function () { function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) { if (rotatedDirection === void 0) { rotatedDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); } if (diff === void 0) { diff = 0; } if (ignore === void 0) { ignore = false; } this.direction = direction; this.rotatedDirection = rotatedDirection; this.diff = diff; this.ignore = ignore; } return FaceDirectionInfo; }()); /** * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera */ var AttachToBoxBehavior = /** @class */ (function () { /** * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera * @param ui The transform node that should be attched to the mesh */ function AttachToBoxBehavior(ui) { this.ui = ui; /** * The name of the behavior */ this.name = "AttachToBoxBehavior"; /** * The distance away from the face of the mesh that the UI should be attached to (default: 0.15) */ this.distanceAwayFromFace = 0.15; /** * The distance from the bottom of the face that the UI should be attached to (default: 0.15) */ this.distanceAwayFromBottomOfFace = 0.15; this._faceVectors = [new FaceDirectionInfo(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up()), new FaceDirectionInfo(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Down()), new FaceDirectionInfo(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Left()), new FaceDirectionInfo(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right()), new FaceDirectionInfo(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward()), new FaceDirectionInfo(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward().scaleInPlace(-1))]; this._tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); this._tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](); this._zeroVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); this._lookAtTmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"](); /* Does nothing */ } /** * Initializes the behavior */ AttachToBoxBehavior.prototype.init = function () { /* Does nothing */ }; AttachToBoxBehavior.prototype._closestFace = function (targetDirection) { var _this = this; // Go over each face and calculate the angle between the face's normal and targetDirection this._faceVectors.forEach(function (v) { if (!_this._target.rotationQuaternion) { _this._target.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z); } _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection); v.diff = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].GetAngleBetweenVectors(v.rotatedDirection, targetDirection, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(v.rotatedDirection, targetDirection)); }); // Return the face information of the one with the normal closeset to target direction return this._faceVectors.reduce(function (min, p) { if (min.ignore) { return p; } else if (p.ignore) { return min; } else { return min.diff < p.diff ? min : p; } }, this._faceVectors[0]); }; AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) { if (up === void 0) { up = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 1, 0); } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix); this._lookAtTmpMatrix.invert(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._lookAtTmpMatrix, ref); }; /** * Attaches the AttachToBoxBehavior to the passed in mesh * @param target The mesh that the specified node will be attached to */ AttachToBoxBehavior.prototype.attach = function (target) { var _this = this; this._target = target; this._scene = this._target.getScene(); // Every frame, update the app bars position this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () { if (!_this._scene.activeCamera) { return; } // Find the face closest to the cameras position var cameraPos = _this._scene.activeCamera.position; if (_this._scene.activeCamera.devicePosition) { cameraPos = _this._scene.activeCamera.devicePosition; } var facing = _this._closestFace(cameraPos.subtract(target.position)); if (_this._scene.activeCamera.leftCamera) { _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix); } else { _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix); } // Get camera up direction _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), _this._tmpMatrix, _this._tmpVector); // Ignore faces to not select a parrelel face for the up vector of the UI _this._faceVectors.forEach(function (v) { if (facing.direction.x && v.direction.x) { v.ignore = true; } if (facing.direction.y && v.direction.y) { v.ignore = true; } if (facing.direction.z && v.direction.z) { v.ignore = true; } }); var facingUp = _this._closestFace(_this._tmpVector); // Unignore faces _this._faceVectors.forEach(function (v) { v.ignore = false; }); // Position the app bar on that face _this.ui.position.copyFrom(target.position); if (facing.direction.x) { facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector); _this.ui.position.addInPlace(_this._tmpVector); } if (facing.direction.y) { facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector); _this.ui.position.addInPlace(_this._tmpVector); } if (facing.direction.z) { facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector); _this.ui.position.addInPlace(_this._tmpVector); } // Rotate to be oriented properly to the camera if (!_this.ui.rotationQuaternion) { _this.ui.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z); } facing.rotatedDirection.scaleToRef(-1, _this._tmpVector); _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion); // Place ui the correct distance from the bottom of the mesh if (facingUp.direction.x) { _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector); } if (facingUp.direction.y) { _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector); } if (facingUp.direction.z) { _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector); } _this.ui.position.addInPlace(_this._tmpVector); }); }; /** * Detaches the behavior from the mesh */ AttachToBoxBehavior.prototype.detach = function () { this._scene.onBeforeRenderObservable.remove(this._onRenderObserver); }; return AttachToBoxBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/fadeInOutBehavior.ts": /*!***********************************************!*\ !*** ./Behaviors/Meshes/fadeInOutBehavior.ts ***! \***********************************************/ /*! exports provided: FadeInOutBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return FadeInOutBehavior; }); /** * A behavior that when attached to a mesh will allow the mesh to fade in and out */ var FadeInOutBehavior = /** @class */ (function () { /** * Instatiates the FadeInOutBehavior */ function FadeInOutBehavior() { var _this = this; /** * Time in milliseconds to delay before fading in (Default: 0) */ this.delay = 0; /** * Time in milliseconds for the mesh to fade in (Default: 300) */ this.fadeInTime = 300; this._millisecondsPerFrame = 1000 / 60; this._hovered = false; this._hoverValue = 0; this._ownerNode = null; this._update = function () { if (_this._ownerNode) { _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame; _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime); if (_this._ownerNode.visibility > 1) { _this._setAllVisibility(_this._ownerNode, 1); _this._hoverValue = _this.fadeInTime + _this.delay; return; } else if (_this._ownerNode.visibility < 0) { _this._setAllVisibility(_this._ownerNode, 0); if (_this._hoverValue < 0) { _this._hoverValue = 0; return; } } setTimeout(_this._update, _this._millisecondsPerFrame); } }; } Object.defineProperty(FadeInOutBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "FadeInOut"; }, enumerable: false, configurable: true }); /** * Initializes the behavior */ FadeInOutBehavior.prototype.init = function () { }; /** * Attaches the fade behavior on the passed in mesh * @param ownerNode The mesh that will be faded in/out once attached */ FadeInOutBehavior.prototype.attach = function (ownerNode) { this._ownerNode = ownerNode; this._setAllVisibility(this._ownerNode, 0); }; /** * Detaches the behavior from the mesh */ FadeInOutBehavior.prototype.detach = function () { this._ownerNode = null; }; /** * Triggers the mesh to begin fading in or out * @param value if the object should fade in or out (true to fade in) */ FadeInOutBehavior.prototype.fadeIn = function (value) { this._hovered = value; this._update(); }; FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) { var _this = this; mesh.visibility = value; mesh.getChildMeshes().forEach(function (c) { _this._setAllVisibility(c, value); }); }; return FadeInOutBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/index.ts": /*!***********************************!*\ !*** ./Behaviors/Meshes/index.ts ***! \***********************************/ /*! exports provided: AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _attachToBoxBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./attachToBoxBehavior */ "./Behaviors/Meshes/attachToBoxBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _attachToBoxBehavior__WEBPACK_IMPORTED_MODULE_0__["AttachToBoxBehavior"]; }); /* harmony import */ var _fadeInOutBehavior__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./fadeInOutBehavior */ "./Behaviors/Meshes/fadeInOutBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _fadeInOutBehavior__WEBPACK_IMPORTED_MODULE_1__["FadeInOutBehavior"]; }); /* harmony import */ var _multiPointerScaleBehavior__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./multiPointerScaleBehavior */ "./Behaviors/Meshes/multiPointerScaleBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _multiPointerScaleBehavior__WEBPACK_IMPORTED_MODULE_2__["MultiPointerScaleBehavior"]; }); /* harmony import */ var _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_3__["PointerDragBehavior"]; }); /* harmony import */ var _sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./sixDofDragBehavior */ "./Behaviors/Meshes/sixDofDragBehavior.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_4__["SixDofDragBehavior"]; }); /***/ }), /***/ "./Behaviors/Meshes/multiPointerScaleBehavior.ts": /*!*******************************************************!*\ !*** ./Behaviors/Meshes/multiPointerScaleBehavior.ts ***! \*******************************************************/ /*! exports provided: MultiPointerScaleBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return MultiPointerScaleBehavior; }); /* harmony import */ var _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /** * A behavior that when attached to a mesh will allow the mesh to be scaled */ var MultiPointerScaleBehavior = /** @class */ (function () { /** * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled */ function MultiPointerScaleBehavior() { this._startDistance = 0; this._initialScale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0); this._targetScale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0); this._sceneRenderObserver = null; this._dragBehaviorA = new _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]({}); this._dragBehaviorA.moveAttached = false; this._dragBehaviorB = new _pointerDragBehavior__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]({}); this._dragBehaviorB.moveAttached = false; } Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "MultiPointerScale"; }, enumerable: false, configurable: true }); /** * Initializes the behavior */ MultiPointerScaleBehavior.prototype.init = function () { }; MultiPointerScaleBehavior.prototype._getCurrentDistance = function () { return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length(); }; /** * Attaches the scale behavior the passed in mesh * @param ownerNode The mesh that will be scaled around once attached */ MultiPointerScaleBehavior.prototype.attach = function (ownerNode) { var _this = this; this._ownerNode = ownerNode; // Create 2 drag behaviors such that each will only be triggered by a separate pointer this._dragBehaviorA.onDragStartObservable.add(function (e) { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) { _this._dragBehaviorA.releaseDrag(); } else { _this._initialScale.copyFrom(ownerNode.scaling); _this._startDistance = _this._getCurrentDistance(); } } }); this._dragBehaviorB.onDragStartObservable.add(function (e) { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) { _this._dragBehaviorB.releaseDrag(); } else { _this._initialScale.copyFrom(ownerNode.scaling); _this._startDistance = _this._getCurrentDistance(); } } }); // Once both drag behaviors are active scale based on the distance between the two pointers [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) { behavior.onDragObservable.add(function () { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { var ratio = _this._getCurrentDistance() / _this._startDistance; _this._initialScale.scaleToRef(ratio, _this._targetScale); } }); }); ownerNode.addBehavior(this._dragBehaviorA); ownerNode.addBehavior(this._dragBehaviorB); // On every frame move towards target scaling to avoid jitter caused by vr controllers this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () { if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) { var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1); if (change.length() > 0.01) { ownerNode.scaling.addInPlace(change); } } }); }; /** * Detaches the behavior from the mesh */ MultiPointerScaleBehavior.prototype.detach = function () { var _this = this; this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) { behavior.onDragStartObservable.clear(); behavior.onDragObservable.clear(); _this._ownerNode.removeBehavior(behavior); }); }; return MultiPointerScaleBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/pointerDragBehavior.ts": /*!*************************************************!*\ !*** ./Behaviors/Meshes/pointerDragBehavior.ts ***! \*************************************************/ /*! exports provided: PointerDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return PointerDragBehavior; }); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/pivotTools */ "./Misc/pivotTools.ts"); /* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts"); /** * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events */ var PointerDragBehavior = /** @class */ (function () { /** * Creates a pointer drag behavior that can be attached to a mesh * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera) */ function PointerDragBehavior(options) { this._useAlternatePickedPointAboveMaxDragAngleDragSpeed = -1.1; /** * The maximum tolerated angle between the drag plane and dragging pointer rays to trigger pointer events. Set to 0 to allow any angle (default: 0) */ this.maxDragAngle = 0; /** * @hidden */ this._useAlternatePickedPointAboveMaxDragAngle = false; /** * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) */ this.currentDraggingPointerID = -1; /** * If the behavior is currently in a dragging state */ this.dragging = false; /** * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) */ this.dragDeltaRatio = 0.2; /** * If the drag plane orientation should be updated during the dragging (Default: true) */ this.updateDragPlane = true; // Debug mode will display drag planes to help visualize behavior this._debugMode = false; this._moving = false; /** * Fires each time the attached mesh is dragged with the pointer * * delta between last drag position and current drag position in world space * * dragDistance along the drag axis * * dragPlaneNormal normal of the current drag plane used during the drag * * dragPlanePoint in world space where the drag intersects the drag plane */ this.onDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Fires each time a drag begins (eg. mouse down on mesh) */ this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Fires each time a drag ends (eg. mouse release after drag) */ this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * If the attached mesh should be moved when dragged */ this.moveAttached = true; /** * If the drag behavior will react to drag events (Default: true) */ this.enabled = true; /** * If pointer events should start and release the drag (Default: true) */ this.startAndReleaseDragOnPointerEvents = true; /** * If camera controls should be detached during the drag */ this.detachCameraControls = true; /** * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true) */ this.useObjectOrientationForDragging = true; /** * Predicate to determine if it is valid to move the object to a new position when it is moved */ this.validateDrag = function (targetPosition) { return true; }; this._tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._alternatePickedPoint = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._worldDragAxis = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._targetPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._attachedElement = null; this._startDragRay = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"]()); this._lastPointerRay = {}; this._dragDelta = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](); // Variables to avoid instantiation in the below method this._pointA = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._pointC = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._localAxis = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._lookAt = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._options = options ? options : {}; var optionCount = 0; if (this._options.dragAxis) { optionCount++; } if (this._options.dragPlaneNormal) { optionCount++; } if (optionCount > 1) { throw "Multiple drag modes specified in dragBehavior options. Only one expected"; } } Object.defineProperty(PointerDragBehavior.prototype, "options", { /** * Gets the options used by the behavior */ get: function () { return this._options; }, /** * Sets the options used by the behavior */ set: function (options) { this._options = options; }, enumerable: false, configurable: true }); Object.defineProperty(PointerDragBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "PointerDrag"; }, enumerable: false, configurable: true }); /** * Initializes the behavior */ PointerDragBehavior.prototype.init = function () { }; /** * Attaches the drag behavior the passed in mesh * @param ownerNode The mesh that will be dragged around once attached * @param predicate Predicate to use for pick filtering */ PointerDragBehavior.prototype.attach = function (ownerNode, predicate) { var _this = this; this._scene = ownerNode.getScene(); this.attachedNode = ownerNode; // Initialize drag plane to not interfere with existing scene if (!PointerDragBehavior._planeScene) { if (this._debugMode) { PointerDragBehavior._planeScene = this._scene; } else { PointerDragBehavior._planeScene = new _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"](this._scene.getEngine(), { virtual: true }); PointerDragBehavior._planeScene.detachControl(); this._scene.onDisposeObservable.addOnce(function () { PointerDragBehavior._planeScene.dispose(); PointerDragBehavior._planeScene = null; }); } } this._dragPlane = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"].CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"].DOUBLESIDE); // State of the drag this.lastDragPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); var pickPredicate = !!predicate ? predicate : function (m) { return _this.attachedNode == m || m.isDescendantOf(_this.attachedNode); }; this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) { if (!_this.enabled) { return; } if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN) { if (_this.startAndReleaseDragOnPointerEvents && !_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) { _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP) { if (_this.startAndReleaseDragOnPointerEvents && _this.currentDraggingPointerID == pointerInfo.event.pointerId) { _this.releaseDrag(); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE) { var pointerId = pointerInfo.event.pointerId; // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") { if (_this._lastPointerRay[_this.currentDraggingPointerID]) { _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID]; delete _this._lastPointerRay[_this.currentDraggingPointerID]; } _this.currentDraggingPointerID = pointerId; } // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag() if (!_this._lastPointerRay[pointerId]) { _this._lastPointerRay[pointerId] = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"]()); } if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) { _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin); _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction); if (_this.currentDraggingPointerID == pointerId && _this.dragging) { _this._moveDrag(pointerInfo.pickInfo.ray); } } } }); this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () { if (_this._moving && _this.moveAttached) { _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedNode); // Slowly move mesh to avoid jitter _this._targetPosition.subtractToRef((_this.attachedNode).absolutePosition, _this._tmpVector); _this._tmpVector.scaleInPlace(_this.dragDeltaRatio); (_this.attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector); if (_this.validateDrag(_this._tmpVector)) { (_this.attachedNode).setAbsolutePosition(_this._tmpVector); } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(_this.attachedNode); } }); }; /** * Force relase the drag action by code. */ PointerDragBehavior.prototype.releaseDrag = function () { if (this.dragging) { this.dragging = false; this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID }); } this.currentDraggingPointerID = -1; this._moving = false; // Reattach camera controls if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) { if (this._scene.activeCamera.getClassName() === "ArcRotateCamera") { var arcRotateCamera = this._scene.activeCamera; arcRotateCamera.attachControl(this._attachedElement, arcRotateCamera.inputs ? arcRotateCamera.inputs.noPreventDefault : true, arcRotateCamera._useCtrlForPanning, arcRotateCamera._panningMouseButton); } else { this._scene.activeCamera.attachControl(this._attachedElement, this._scene.activeCamera.inputs ? this._scene.activeCamera.inputs.noPreventDefault : true); } } }; /** * Simulates the start of a pointer drag event on the behavior * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID) * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh) * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position) */ PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) { if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; } this._startDrag(pointerId, fromRay, startPickedPoint); var lastRay = this._lastPointerRay[pointerId]; if (pointerId === PointerDragBehavior._AnyMouseID) { lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]]; } if (lastRay) { // if there was a last pointer ray drag the object there this._moveDrag(lastRay); } }; PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) { if (!this._scene.activeCamera || this.dragging || !this.attachedNode) { return; } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(this.attachedNode); // Create start ray from the camera to the object if (fromRay) { this._startDragRay.direction.copyFrom(fromRay.direction); this._startDragRay.origin.copyFrom(fromRay.origin); } else { this._startDragRay.origin.copyFrom(this._scene.activeCamera.position); this.attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector); this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction); } this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector); var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay); if (pickedPoint) { this.dragging = true; this.currentDraggingPointerID = pointerId; this.lastDragPosition.copyFrom(pickedPoint); this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID }); this._targetPosition.copyFrom((this.attachedNode).absolutePosition); // Detatch camera controls if (this.detachCameraControls && this._scene.activeCamera && this._scene.activeCamera.inputs && !this._scene.activeCamera.leftCamera) { if (this._scene.activeCamera.inputs.attachedElement) { this._attachedElement = this._scene.activeCamera.inputs.attachedElement; this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement); } else { this._attachedElement = null; } } } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(this.attachedNode); }; PointerDragBehavior.prototype._moveDrag = function (ray) { this._moving = true; var pickedPoint = this._pickWithRayOnDragPlane(ray); if (pickedPoint) { if (this.updateDragPlane) { this._updateDragPlanePosition(ray, pickedPoint); } var dragLength = 0; // depending on the drag mode option drag accordingly if (this._options.dragAxis) { // Convert local drag axis to world if useObjectOrientationForDragging this.useObjectOrientationForDragging ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis) : this._worldDragAxis.copyFrom(this._options.dragAxis); // Project delta drag from the drag plane onto the drag axis pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector); dragLength = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._tmpVector, this._worldDragAxis); this._worldDragAxis.scaleToRef(dragLength, this._dragDelta); } else { dragLength = this._dragDelta.length(); pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta); } this._targetPosition.addInPlace(this._dragDelta); this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID }); this.lastDragPosition.copyFrom(pickedPoint); } }; PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) { var _this = this; if (!ray) { return null; } // Calculate angle between plane normal and ray var angle = Math.acos(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._dragPlane.forward, ray.direction)); // Correct if ray is casted from oposite side if (angle > Math.PI / 2) { angle = Math.PI - angle; } // If the angle is too perpendicular to the plane pick another point on the plane where it is looking if (this.maxDragAngle > 0 && angle > this.maxDragAngle) { if (this._useAlternatePickedPointAboveMaxDragAngle) { // Invert ray direction along the towards object axis this._tmpVector.copyFrom(ray.direction); (this.attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint); this._alternatePickedPoint.normalize(); this._alternatePickedPoint.scaleInPlace(this._useAlternatePickedPointAboveMaxDragAngleDragSpeed * _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._alternatePickedPoint, this._tmpVector)); this._tmpVector.addInPlace(this._alternatePickedPoint); // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point var dot = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._dragPlane.forward, this._tmpVector); this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint); this._alternatePickedPoint.addInPlace(this._tmpVector); this._alternatePickedPoint.addInPlace((this.attachedNode).absolutePosition); return this._alternatePickedPoint; } else { return null; } } var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; }); if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) { return pickResult.pickedPoint; } else { return null; } }; // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) { this._pointA.copyFrom(dragPlanePosition); if (this._options.dragAxis) { this.useObjectOrientationForDragging ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragAxis, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis); // Calculate plane normal that is the cross product of local axis and (eye-dragPlanePosition) ray.origin.subtractToRef(this._pointA, this._pointC); this._pointC.normalize(); if (Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(this._localAxis, this._pointC)) > 0.999) { // the drag axis is colinear with the (eye to position) ray. The cross product will give jittered values. // A new axis vector need to be computed if (Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._pointC)) > 0.999) { this._lookAt.copyFrom(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Right()); } else { this._lookAt.copyFrom(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly); } } else { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CrossToRef(this._localAxis, this._pointC, this._lookAt); // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].CrossToRef(this._localAxis, this._lookAt, this._lookAt); this._lookAt.normalize(); } this._dragPlane.position.copyFrom(this._pointA); this._pointA.addToRef(this._lookAt, this._lookAt); this._dragPlane.lookAt(this._lookAt); } else if (this._options.dragPlaneNormal) { this.useObjectOrientationForDragging ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._options.dragPlaneNormal, this.attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal); this._dragPlane.position.copyFrom(this._pointA); this._pointA.addToRef(this._localAxis, this._lookAt); this._dragPlane.lookAt(this._lookAt); } else { this._dragPlane.position.copyFrom(this._pointA); this._dragPlane.lookAt(ray.origin); } // Update the position of the drag plane so it doesn't get out of sync with the node (eg. when moving back and forth quickly) this._dragPlane.position.copyFrom(this.attachedNode.absolutePosition); this._dragPlane.computeWorldMatrix(true); }; /** * Detaches the behavior from the mesh */ PointerDragBehavior.prototype.detach = function () { if (this._pointerObserver) { this._scene.onPointerObservable.remove(this._pointerObserver); } if (this._beforeRenderObserver) { this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver); } this.releaseDrag(); }; PointerDragBehavior._AnyMouseID = -2; return PointerDragBehavior; }()); /***/ }), /***/ "./Behaviors/Meshes/sixDofDragBehavior.ts": /*!************************************************!*\ !*** ./Behaviors/Meshes/sixDofDragBehavior.ts ***! \************************************************/ /*! exports provided: SixDofDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return SixDofDragBehavior; }); /* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts"); /* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../scene */ "./scene.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Misc/pivotTools */ "./Misc/pivotTools.ts"); /** * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray */ var SixDofDragBehavior = /** @class */ (function () { /** * Instantiates a behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray */ function SixDofDragBehavior() { this._sceneRenderObserver = null; this._targetPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); this._moving = false; this._startingOrientation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); this._attachedElement = null; /** * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 3) */ this.zDragFactor = 3; /** * If the object should rotate to face the drag origin */ this.rotateDraggedObject = true; /** * If the behavior is currently in a dragging state */ this.dragging = false; /** * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2) */ this.dragDeltaRatio = 0.2; /** * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active) */ this.currentDraggingPointerID = -1; /** * If camera controls should be detached during the drag */ this.detachCameraControls = true; /** * Fires each time a drag starts */ this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); /** * Fires each time a drag ends (eg. mouse release after drag) */ this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); } Object.defineProperty(SixDofDragBehavior.prototype, "name", { /** * The name of the behavior */ get: function () { return "SixDofDrag"; }, enumerable: false, configurable: true }); /** * Initializes the behavior */ SixDofDragBehavior.prototype.init = function () { }; Object.defineProperty(SixDofDragBehavior.prototype, "_pointerCamera", { /** * In the case of multiplea active cameras, the cameraToUseForPointers should be used if set instead of active camera */ get: function () { if (this._scene.cameraToUseForPointers) { return this._scene.cameraToUseForPointers; } else { return this._scene.activeCamera; } }, enumerable: false, configurable: true }); /** * Attaches the scale behavior the passed in mesh * @param ownerNode The mesh that will be scaled around once attached */ SixDofDragBehavior.prototype.attach = function (ownerNode) { var _this = this; this._ownerNode = ownerNode; this._scene = this._ownerNode.getScene(); if (!SixDofDragBehavior._virtualScene) { SixDofDragBehavior._virtualScene = new _scene__WEBPACK_IMPORTED_MODULE_1__["Scene"](this._scene.getEngine()); SixDofDragBehavior._virtualScene.detachControl(); this._scene.getEngine().scenes.pop(); } var pickedMesh = null; var lastSixDofOriginPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0); // Setup virtual meshes to be used for dragging without dirtying the existing scene this._virtualOriginMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]("", SixDofDragBehavior._virtualScene); this._virtualOriginMesh.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); this._virtualDragMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]("", SixDofDragBehavior._virtualScene); this._virtualDragMesh.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); var pickPredicate = function (m) { return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode); }; this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) { if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERDOWN) { if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) { if (_this._pointerCamera && _this._pointerCamera.cameraRigMode == _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].RIG_MODE_NONE) { pointerInfo.pickInfo.ray.origin.copyFrom(_this._pointerCamera.globalPosition); } pickedMesh = _this._ownerNode; _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(pickedMesh); lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin); // Set position and orientation of the controller _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction)); // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); pickedMesh.computeWorldMatrix(); _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition); if (!pickedMesh.rotationQuaternion) { pickedMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z); } var oldParent = pickedMesh.parent; pickedMesh.setParent(null); _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion); pickedMesh.setParent(oldParent); _this._virtualOriginMesh.addChild(_this._virtualDragMesh); // Update state _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition); _this.dragging = true; _this.currentDraggingPointerID = pointerInfo.event.pointerId; // Detatch camera controls if (_this.detachCameraControls && _this._pointerCamera && !_this._pointerCamera.leftCamera) { if (_this._pointerCamera.inputs.attachedElement) { _this._attachedElement = _this._pointerCamera.inputs.attachedElement; _this._pointerCamera.detachControl(_this._pointerCamera.inputs.attachedElement); } else { _this._attachedElement = null; } } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(pickedMesh); _this.onDragStartObservable.notifyObservers({}); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERUP || pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERDOUBLETAP) { if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) { _this.dragging = false; _this._moving = false; _this.currentDraggingPointerID = -1; pickedMesh = null; _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); // Reattach camera controls if (_this.detachCameraControls && _this._attachedElement && _this._pointerCamera && !_this._pointerCamera.leftCamera) { _this._pointerCamera.attachControl(_this._attachedElement, true); } _this.onDragEndObservable.notifyObservers({}); } } else if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_2__["PointerEventTypes"].POINTERMOVE) { if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) { var zDragFactor = _this.zDragFactor; if (_this._pointerCamera && _this._pointerCamera.cameraRigMode == _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].RIG_MODE_NONE) { pointerInfo.pickInfo.ray.origin.copyFrom(_this._pointerCamera.globalPosition); zDragFactor = 0; } // Calculate controller drag distance in controller space var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition); lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin); var localOriginDragDifference = -_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(originDragDifference, pointerInfo.pickInfo.ray.direction); _this._virtualOriginMesh.addChild(_this._virtualDragMesh); // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z; if (_this._virtualDragMesh.position.z < 0) { _this._virtualDragMesh.position.z = 0; } // Update the controller position _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin); _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.add(pointerInfo.pickInfo.ray.direction)); _this._virtualOriginMesh.removeChild(_this._virtualDragMesh); // Move the virtualObjectsPosition into the picked mesh's space if needed _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition); if (pickedMesh.parent) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._targetPosition, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition); } if (!_this._moving) { _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion); } _this._moving = true; } } }); var tmpQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](); // On every frame move towards target scaling to avoid jitter caused by vr controllers this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () { if (_this.dragging && _this._moving && pickedMesh) { _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RemoveAndStorePivotPoint(pickedMesh); // Slowly move mesh to avoid jitter pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio)); if (_this.rotateDraggedObject) { // Get change in rotation tmpQuaternion.copyFrom(_this._startingOrientation); tmpQuaternion.x = -tmpQuaternion.x; tmpQuaternion.y = -tmpQuaternion.y; tmpQuaternion.z = -tmpQuaternion.z; _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion); // Convert change in rotation to only y axis rotation _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion); tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion); // Slowly move mesh to avoid jitter var oldParent = pickedMesh.parent; // Only rotate the mesh if it's parent has uniform scaling if (!oldParent || (oldParent.scaling && !oldParent.scaling.isNonUniformWithinEpsilon(0.001))) { pickedMesh.setParent(null); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion); pickedMesh.setParent(oldParent); } } _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_6__["PivotTools"]._RestorePivotPoint(pickedMesh); } }); }; /** * Detaches the behavior from the mesh */ SixDofDragBehavior.prototype.detach = function () { if (this._scene) { if (this.detachCameraControls && this._attachedElement && this._pointerCamera && !this._pointerCamera.leftCamera) { this._pointerCamera.attachControl(this._attachedElement, true); } this._scene.onPointerObservable.remove(this._pointerObserver); } if (this._ownerNode) { this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver); } if (this._virtualOriginMesh) { this._virtualOriginMesh.dispose(); } if (this._virtualDragMesh) { this._virtualDragMesh.dispose(); } this.onDragEndObservable.clear(); this.onDragStartObservable.clear(); }; return SixDofDragBehavior; }()); /***/ }), /***/ "./Behaviors/behavior.ts": /*!*******************************!*\ !*** ./Behaviors/behavior.ts ***! \*******************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /***/ }), /***/ "./Behaviors/index.ts": /*!****************************!*\ !*** ./Behaviors/index.ts ***! \****************************/ /*! exports provided: AutoRotationBehavior, BouncingBehavior, FramingBehavior, AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _behavior__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./behavior */ "./Behaviors/behavior.ts"); /* empty/unused harmony star reexport *//* harmony import */ var _Cameras_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Cameras/index */ "./Behaviors/Cameras/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_1__["AutoRotationBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_1__["BouncingBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _Cameras_index__WEBPACK_IMPORTED_MODULE_1__["FramingBehavior"]; }); /* harmony import */ var _Meshes_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Meshes/index */ "./Behaviors/Meshes/index.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_2__["AttachToBoxBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_2__["FadeInOutBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_2__["MultiPointerScaleBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_2__["PointerDragBehavior"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _Meshes_index__WEBPACK_IMPORTED_MODULE_2__["SixDofDragBehavior"]; }); /***/ }), /***/ "./Bones/bone.ts": /*!***********************!*\ !*** ./Bones/bone.ts ***! \***********************/ /*! exports provided: Bone */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return Bone; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts"); /* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts"); /** * Class used to store bone information * @see https://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ var Bone = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Bone, _super); /** * Create a new bone * @param name defines the bone name * @param skeleton defines the parent skeleton * @param parentBone defines the parent (can be null if the bone is the root) * @param localMatrix defines the local matrix * @param restPose defines the rest pose matrix * @param baseMatrix defines the base matrix * @param index defines index of the bone in the hiearchy */ function Bone( /** * defines the bone name */ name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) { if (parentBone === void 0) { parentBone = null; } if (localMatrix === void 0) { localMatrix = null; } if (restPose === void 0) { restPose = null; } if (baseMatrix === void 0) { baseMatrix = null; } if (index === void 0) { index = null; } var _this = _super.call(this, name, skeleton.getScene()) || this; _this.name = name; /** * Gets the list of child bones */ _this.children = new Array(); /** Gets the animations associated with this bone */ _this.animations = new Array(); /** * @hidden Internal only * Set this value to map this bone to a different index in the transform matrices * Set this value to -1 to exclude the bone from the transform matrices */ _this._index = null; _this._absoluteTransform = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); _this._invertedAbsoluteTransform = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); _this._scalingDeterminant = 1; _this._worldTransform = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); _this._needToDecompose = true; _this._needToCompose = false; /** @hidden */ _this._linkedTransformNode = null; /** @hidden */ _this._waitingTransformNodeId = null; _this._skeleton = skeleton; _this._localMatrix = localMatrix ? localMatrix.clone() : _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); _this._restPose = restPose ? restPose : _this._localMatrix.clone(); _this._bindPose = _this._localMatrix.clone(); _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone(); _this._index = index; skeleton.bones.push(_this); _this.setParent(parentBone, false); if (baseMatrix || localMatrix) { _this._updateDifferenceMatrix(); } return _this; } Object.defineProperty(Bone.prototype, "_matrix", { /** @hidden */ get: function () { this._compose(); return this._localMatrix; }, /** @hidden */ set: function (value) { this._localMatrix.copyFrom(value); this._needToDecompose = true; }, enumerable: false, configurable: true }); /** * Gets the current object class name. * @return the class name */ Bone.prototype.getClassName = function () { return "Bone"; }; // Members /** * Gets the parent skeleton * @returns a skeleton */ Bone.prototype.getSkeleton = function () { return this._skeleton; }; /** * Gets parent bone * @returns a bone or null if the bone is the root of the bone hierarchy */ Bone.prototype.getParent = function () { return this._parent; }; /** * Returns an array containing the root bones * @returns an array containing the root bones */ Bone.prototype.getChildren = function () { return this.children; }; /** * Gets the node index in matrix array generated for rendering * @returns the node index */ Bone.prototype.getIndex = function () { return this._index === null ? this.getSkeleton().bones.indexOf(this) : this._index; }; /** * Sets the parent bone * @param parent defines the parent (can be null if the bone is the root) * @param updateDifferenceMatrix defines if the difference matrix must be updated */ Bone.prototype.setParent = function (parent, updateDifferenceMatrix) { if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } if (this._parent === parent) { return; } if (this._parent) { var index = this._parent.children.indexOf(this); if (index !== -1) { this._parent.children.splice(index, 1); } } this._parent = parent; if (this._parent) { this._parent.children.push(this); } if (updateDifferenceMatrix) { this._updateDifferenceMatrix(); } this.markAsDirty(); }; /** * Gets the local matrix * @returns a matrix */ Bone.prototype.getLocalMatrix = function () { this._compose(); return this._localMatrix; }; /** * Gets the base matrix (initial matrix which remains unchanged) * @returns a matrix */ Bone.prototype.getBaseMatrix = function () { return this._baseMatrix; }; /** * Gets the rest pose matrix * @returns a matrix */ Bone.prototype.getRestPose = function () { return this._restPose; }; /** * Sets the rest pose matrix * @param matrix the local-space rest pose to set for this bone */ Bone.prototype.setRestPose = function (matrix) { this._restPose.copyFrom(matrix); }; /** * Gets the bind pose matrix * @returns the bind pose matrix */ Bone.prototype.getBindPose = function () { return this._bindPose; }; /** * Sets the bind pose matrix * @param matrix the local-space bind pose to set for this bone */ Bone.prototype.setBindPose = function (matrix) { this._bindPose.copyFrom(matrix); }; /** * Gets a matrix used to store world matrix (ie. the matrix sent to shaders) */ Bone.prototype.getWorldMatrix = function () { return this._worldTransform; }; /** * Sets the local matrix to rest pose matrix */ Bone.prototype.returnToRest = function () { if (this._skeleton._numBonesWithLinkedTransformNode > 0) { this.updateMatrix(this._restPose.clone(), false, false); } else { this.updateMatrix(this._restPose.clone()); } }; /** * Gets the inverse of the absolute transform matrix. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state) * @returns a matrix */ Bone.prototype.getInvertedAbsoluteTransform = function () { return this._invertedAbsoluteTransform; }; /** * Gets the absolute transform matrix (ie base matrix * parent world matrix) * @returns a matrix */ Bone.prototype.getAbsoluteTransform = function () { return this._absoluteTransform; }; /** * Links with the given transform node. * The local matrix of this bone is copied from the transform node every frame. * @param transformNode defines the transform node to link to */ Bone.prototype.linkTransformNode = function (transformNode) { if (this._linkedTransformNode) { this._skeleton._numBonesWithLinkedTransformNode--; } this._linkedTransformNode = transformNode; if (this._linkedTransformNode) { this._skeleton._numBonesWithLinkedTransformNode++; } }; // Properties (matches AbstractMesh properties) /** * Gets the node used to drive the bone's transformation * @returns a transform node or null */ Bone.prototype.getTransformNode = function () { return this._linkedTransformNode; }; Object.defineProperty(Bone.prototype, "position", { /** Gets or sets current position (in local space) */ get: function () { this._decompose(); return this._localPosition; }, set: function (newPosition) { this._decompose(); this._localPosition.copyFrom(newPosition); this._markAsDirtyAndCompose(); }, enumerable: false, configurable: true }); Object.defineProperty(Bone.prototype, "rotation", { /** Gets or sets current rotation (in local space) */ get: function () { return this.getRotation(); }, set: function (newRotation) { this.setRotation(newRotation); }, enumerable: false, configurable: true }); Object.defineProperty(Bone.prototype, "rotationQuaternion", { /** Gets or sets current rotation quaternion (in local space) */ get: function () { this._decompose(); return this._localRotation; }, set: function (newRotation) { this.setRotationQuaternion(newRotation); }, enumerable: false, configurable: true }); Object.defineProperty(Bone.prototype, "scaling", { /** Gets or sets current scaling (in local space) */ get: function () { return this.getScale(); }, set: function (newScaling) { this.setScale(newScaling); }, enumerable: false, configurable: true }); Object.defineProperty(Bone.prototype, "animationPropertiesOverride", { /** * Gets the animation properties override */ get: function () { return this._skeleton.animationPropertiesOverride; }, enumerable: false, configurable: true }); // Methods Bone.prototype._decompose = function () { if (!this._needToDecompose) { return; } this._needToDecompose = false; if (!this._localScaling) { this._localScaling = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this._localRotation = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Zero(); this._localPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); } this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition); }; Bone.prototype._compose = function () { if (!this._needToCompose) { return; } if (!this._localScaling) { this._needToCompose = false; return; } this._needToCompose = false; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix); }; /** * Update the base and local matrices * @param matrix defines the new base or local matrix * @param updateDifferenceMatrix defines if the difference matrix must be updated * @param updateLocalMatrix defines if the local matrix should be updated */ Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) { if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; } if (updateLocalMatrix === void 0) { updateLocalMatrix = true; } this._baseMatrix.copyFrom(matrix); if (updateDifferenceMatrix) { this._updateDifferenceMatrix(); } if (updateLocalMatrix) { this._localMatrix.copyFrom(matrix); this._markAsDirtyAndDecompose(); } else { this.markAsDirty(); } }; /** @hidden */ Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) { if (updateChildren === void 0) { updateChildren = true; } if (!rootMatrix) { rootMatrix = this._baseMatrix; } if (this._parent) { rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); } else { this._absoluteTransform.copyFrom(rootMatrix); } this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform); if (updateChildren) { for (var index = 0; index < this.children.length; index++) { this.children[index]._updateDifferenceMatrix(); } } this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1); }; /** * Flag the bone as dirty (Forcing it to update everything) */ Bone.prototype.markAsDirty = function () { this._currentRenderId++; this._childUpdateId++; this._skeleton._markAsDirty(); }; /** @hidden */ Bone.prototype._markAsDirtyAndCompose = function () { this.markAsDirty(); this._needToCompose = true; }; Bone.prototype._markAsDirtyAndDecompose = function () { this.markAsDirty(); this._needToDecompose = true; }; /** * Translate the bone in local or world space * @param vec The amount to translate the bone * @param space The space that the translation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.translate = function (vec, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } var lm = this.getLocalMatrix(); if (space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { lm.addAtIndex(12, vec.x); lm.addAtIndex(13, vec.y); lm.addAtIndex(14, vec.z); } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; var tvec = Bone._tmpVecs[0]; if (this._parent) { if (mesh && wm) { tmat.copyFrom(this._parent.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat.copyFrom(this._parent.getAbsoluteTransform()); } } else { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityToRef(tmat); } tmat.setTranslationFromFloats(0, 0, 0); tmat.invert(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(vec, tmat, tvec); lm.addAtIndex(12, tvec.x); lm.addAtIndex(13, tvec.y); lm.addAtIndex(14, tvec.z); } this._markAsDirtyAndDecompose(); }; /** * Set the postion of the bone in local or world space * @param position The position to set the bone * @param space The space that the position is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setPosition = function (position, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } var lm = this.getLocalMatrix(); if (space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { lm.setTranslationFromFloats(position.x, position.y, position.z); } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; var vec = Bone._tmpVecs[0]; if (this._parent) { if (mesh && wm) { tmat.copyFrom(this._parent.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat.copyFrom(this._parent.getAbsoluteTransform()); } tmat.invert(); } else { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityToRef(tmat); } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, vec); lm.setTranslationFromFloats(vec.x, vec.y, vec.z); } this._markAsDirtyAndDecompose(); }; /** * Set the absolute position of the bone (world space) * @param position The position to set the bone * @param mesh The mesh that this bone is attached to */ Bone.prototype.setAbsolutePosition = function (position, mesh) { this.setPosition(position, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].WORLD, mesh); }; /** * Scale the bone on the x, y and z axes (in local space) * @param x The amount to scale the bone on the x axis * @param y The amount to scale the bone on the y axis * @param z The amount to scale the bone on the z axis * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default) */ Bone.prototype.scale = function (x, y, z, scaleChildren) { if (scaleChildren === void 0) { scaleChildren = false; } var locMat = this.getLocalMatrix(); // Apply new scaling on top of current local matrix var scaleMat = Bone._tmpMats[0]; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ScalingToRef(x, y, z, scaleMat); scaleMat.multiplyToRef(locMat, locMat); // Invert scaling matrix and apply the inverse to all children scaleMat.invert(); for (var _i = 0, _a = this.children; _i < _a.length; _i++) { var child = _a[_i]; var cm = child.getLocalMatrix(); cm.multiplyToRef(scaleMat, cm); cm.multiplyAtIndex(12, x); cm.multiplyAtIndex(13, y); cm.multiplyAtIndex(14, z); child._markAsDirtyAndDecompose(); } this._markAsDirtyAndDecompose(); if (scaleChildren) { for (var _b = 0, _c = this.children; _b < _c.length; _b++) { var child = _c[_b]; child.scale(x, y, z, scaleChildren); } } }; /** * Set the bone scaling in local space * @param scale defines the scaling vector */ Bone.prototype.setScale = function (scale) { this._decompose(); this._localScaling.copyFrom(scale); this._markAsDirtyAndCompose(); }; /** * Gets the current scaling in local space * @returns the current scaling vector */ Bone.prototype.getScale = function () { this._decompose(); return this._localScaling; }; /** * Gets the current scaling in local space and stores it in a target vector * @param result defines the target vector */ Bone.prototype.getScaleToRef = function (result) { this._decompose(); result.copyFrom(this._localScaling); }; /** * Set the yaw, pitch, and roll of the bone in local or world space * @param yaw The rotation of the bone on the y axis * @param pitch The rotation of the bone on the x axis * @param roll The rotation of the bone on the z axis * @param space The space that the axes of rotation are in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (space === _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { var quat = Bone._tmpQuat; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationYawPitchRollToRef(yaw, pitch, roll, quat); this.setRotationQuaternion(quat, space, mesh); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat = Bone._tmpMats[1]; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(yaw, pitch, roll, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Add a rotation to the bone on an axis in local or world space * @param axis The axis to rotate the bone on * @param amount The amount to rotate the bone * @param space The space that the axis is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.rotate = function (axis, amount, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } var rmat = Bone._tmpMats[0]; rmat.setTranslationFromFloats(0, 0, 0); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationAxisToRef(axis, amount, rmat); this._rotateWithMatrix(rmat, space, mesh); }; /** * Set the rotation of the bone to a particular axis angle in local or world space * @param axis The axis to rotate the bone on * @param angle The angle that the bone should be rotated to * @param space The space that the axis is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (space === _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { var quat = Bone._tmpQuat; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationAxisToRef(axis, angle, quat); this.setRotationQuaternion(quat, space, mesh); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat = Bone._tmpMats[1]; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationAxisToRef(axis, angle, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Set the euler rotation of the bone in local of world space * @param rotation The euler rotation that the bone should be set to * @param space The space that the rotation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setRotation = function (rotation, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh); }; /** * Set the quaternion rotation of the bone in local of world space * @param quat The quaternion rotation that the bone should be set to * @param space The space that the rotation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setRotationQuaternion = function (quat, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (space === _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { this._decompose(); this._localRotation.copyFrom(quat); this._markAsDirtyAndCompose(); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat = Bone._tmpMats[1]; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromQuaternionToRef(quat, rotMat); rotMatInv.multiplyToRef(rotMat, rotMat); this._rotateWithMatrix(rotMat, space, mesh); }; /** * Set the rotation matrix of the bone in local of world space * @param rotMat The rotation matrix that the bone should be set to * @param space The space that the rotation is in * @param mesh The mesh that this bone is attached to. This is only used in world space */ Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (space === _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { var quat = Bone._tmpQuat; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(rotMat, quat); this.setRotationQuaternion(quat, space, mesh); return; } var rotMatInv = Bone._tmpMats[0]; if (!this._getNegativeRotationToRef(rotMatInv, mesh)) { return; } var rotMat2 = Bone._tmpMats[1]; rotMat2.copyFrom(rotMat); rotMatInv.multiplyToRef(rotMat, rotMat2); this._rotateWithMatrix(rotMat2, space, mesh); }; Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } var lmat = this.getLocalMatrix(); var lx = lmat.m[12]; var ly = lmat.m[13]; var lz = lmat.m[14]; var parent = this.getParent(); var parentScale = Bone._tmpMats[3]; var parentScaleInv = Bone._tmpMats[4]; if (parent && space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].WORLD) { if (mesh) { parentScale.copyFrom(mesh.getWorldMatrix()); parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale); } else { parentScale.copyFrom(parent.getAbsoluteTransform()); } parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { if (space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].WORLD && mesh) { parentScale.copyFrom(mesh.getWorldMatrix()); parentScaleInv.copyFrom(parentScale); parentScaleInv.invert(); lmat.multiplyToRef(parentScale, lmat); lmat.multiplyToRef(rmat, lmat); lmat.multiplyToRef(parentScaleInv, lmat); } else { lmat.multiplyToRef(rmat, lmat); } } lmat.setTranslationFromFloats(lx, ly, lz); this.computeAbsoluteTransforms(); this._markAsDirtyAndDecompose(); }; Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) { var scaleMatrix = Bone._tmpMats[2]; rotMatInv.copyFrom(this.getAbsoluteTransform()); if (mesh) { rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix); } rotMatInv.invert(); if (isNaN(rotMatInv.m[0])) { // Matrix failed to invert. // This can happen if scale is zero for example. return false; } scaleMatrix.multiplyAtIndex(0, this._scalingDeterminant); rotMatInv.multiplyToRef(scaleMatrix, rotMatInv); return true; }; /** * Get the position of the bone in local or world space * @param space The space that the returned position is in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The position of the bone */ Bone.prototype.getPosition = function (space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var pos = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getPositionToRef(space, mesh, pos); return pos; }; /** * Copy the position of the bone to a vector3 in local or world space * @param space The space that the returned position is in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The vector3 to copy the position to */ Bone.prototype.getPositionToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { var lm = this.getLocalMatrix(); result.x = lm.m[12]; result.y = lm.m[13]; result.z = lm.m[14]; } else { var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; if (mesh && wm) { tmat.copyFrom(this.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat = this.getAbsoluteTransform(); } result.x = tmat.m[12]; result.y = tmat.m[13]; result.z = tmat.m[14]; } }; /** * Get the absolute position of the bone (world space) * @param mesh The mesh that this bone is attached to * @returns The absolute position of the bone */ Bone.prototype.getAbsolutePosition = function (mesh) { if (mesh === void 0) { mesh = null; } var pos = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getPositionToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].WORLD, mesh, pos); return pos; }; /** * Copy the absolute position of the bone (world space) to the result param * @param mesh The mesh that this bone is attached to * @param result The vector3 to copy the absolute position to */ Bone.prototype.getAbsolutePositionToRef = function (mesh, result) { this.getPositionToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].WORLD, mesh, result); }; /** * Compute the absolute transforms of this bone and its children */ Bone.prototype.computeAbsoluteTransforms = function () { this._compose(); if (this._parent) { this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform); } else { this._absoluteTransform.copyFrom(this._localMatrix); var poseMatrix = this._skeleton.getPoseMatrix(); if (poseMatrix) { this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform); } } var children = this.children; var len = children.length; for (var i = 0; i < len; i++) { children[i].computeAbsoluteTransforms(); } }; /** * Get the world direction from an axis that is in the local space of the bone * @param localAxis The local direction that is used to compute the world direction * @param mesh The mesh that this bone is attached to * @returns The world direction */ Bone.prototype.getDirection = function (localAxis, mesh) { if (mesh === void 0) { mesh = null; } var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getDirectionToRef(localAxis, mesh, result); return result; }; /** * Copy the world direction to a vector3 from an axis that is in the local space of the bone * @param localAxis The local direction that is used to compute the world direction * @param mesh The mesh that this bone is attached to * @param result The vector3 that the world direction will be copied to */ Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var mat = Bone._tmpMats[0]; mat.copyFrom(this.getAbsoluteTransform()); if (mesh && wm) { mat.multiplyToRef(wm, mat); } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(localAxis, mat, result); result.normalize(); }; /** * Get the euler rotation of the bone in local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The euler rotation */ Bone.prototype.getRotation = function (space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getRotationToRef(space, mesh, result); return result; }; /** * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The vector3 that the rotation should be copied to */ Bone.prototype.getRotationToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var quat = Bone._tmpQuat; this.getRotationQuaternionToRef(space, mesh, quat); quat.toEulerAnglesToRef(result); }; /** * Get the quaternion rotation of the bone in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The quaternion rotation */ Bone.prototype.getRotationQuaternion = function (space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); this.getRotationQuaternionToRef(space, mesh, result); return result; }; /** * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The quaternion that the rotation should be copied to */ Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (mesh === void 0) { mesh = null; } if (space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { this._decompose(); result.copyFrom(this._localRotation); } else { var mat = Bone._tmpMats[0]; var amat = this.getAbsoluteTransform(); if (mesh) { amat.multiplyToRef(mesh.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.multiplyAtIndex(0, this._scalingDeterminant); mat.multiplyAtIndex(1, this._scalingDeterminant); mat.multiplyAtIndex(2, this._scalingDeterminant); mat.decompose(undefined, result, undefined); } }; /** * Get the rotation matrix of the bone in local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @returns The rotation matrix */ Bone.prototype.getRotationMatrix = function (space, mesh) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); this.getRotationMatrixToRef(space, mesh, result); return result; }; /** * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space * @param space The space that the rotation should be in * @param mesh The mesh that this bone is attached to. This is only used in world space * @param result The quaternion that the rotation should be copied to */ Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) { if (space === void 0) { space = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL; } if (space == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Space"].LOCAL) { this.getLocalMatrix().getRotationMatrixToRef(result); } else { var mat = Bone._tmpMats[0]; var amat = this.getAbsoluteTransform(); if (mesh) { amat.multiplyToRef(mesh.getWorldMatrix(), mat); } else { mat.copyFrom(amat); } mat.multiplyAtIndex(0, this._scalingDeterminant); mat.multiplyAtIndex(1, this._scalingDeterminant); mat.multiplyAtIndex(2, this._scalingDeterminant); mat.getRotationMatrixToRef(result); } }; /** * Get the world position of a point that is in the local space of the bone * @param position The local position * @param mesh The mesh that this bone is attached to * @returns The world position */ Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) { if (mesh === void 0) { mesh = null; } var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getAbsolutePositionFromLocalToRef(position, mesh, result); return result; }; /** * Get the world position of a point that is in the local space of the bone and copy it to the result param * @param position The local position * @param mesh The mesh that this bone is attached to * @param result The vector3 that the world position should be copied to */ Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; if (mesh && wm) { tmat.copyFrom(this.getAbsoluteTransform()); tmat.multiplyToRef(wm, tmat); } else { tmat = this.getAbsoluteTransform(); } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, result); }; /** * Get the local position of a point that is in world space * @param position The world position * @param mesh The mesh that this bone is attached to * @returns The local position */ Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) { if (mesh === void 0) { mesh = null; } var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(); this.getLocalPositionFromAbsoluteToRef(position, mesh, result); return result; }; /** * Get the local position of a point that is in world space and copy it to the result param * @param position The world position * @param mesh The mesh that this bone is attached to * @param result The vector3 that the local position should be copied to */ Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) { if (mesh === void 0) { mesh = null; } var wm = null; //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms() if (mesh) { wm = mesh.getWorldMatrix(); } this._skeleton.computeAbsoluteTransforms(); var tmat = Bone._tmpMats[0]; tmat.copyFrom(this.getAbsoluteTransform()); if (mesh && wm) { tmat.multiplyToRef(wm, tmat); } tmat.invert(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(position, tmat, result); }; Bone._tmpVecs = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__["ArrayTools"].BuildArray(2, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); Bone._tmpQuat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); Bone._tmpMats = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_2__["ArrayTools"].BuildArray(5, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity); return Bone; }(_node__WEBPACK_IMPORTED_MODULE_3__["Node"])); /***/ }), /***/ "./Bones/boneIKController.ts": /*!***********************************!*\ !*** ./Bones/boneIKController.ts ***! \***********************************/ /*! exports provided: BoneIKController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return BoneIKController; }); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts"); /** * Class used to apply inverse kinematics to bones * @see https://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller */ var BoneIKController = /** @class */ (function () { /** * Creates a new BoneIKController * @param mesh defines the mesh to control * @param bone defines the bone to control * @param options defines options to set up the controller */ function BoneIKController(mesh, bone, options) { /** * Gets or sets the target position */ this.targetPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** * Gets or sets the pole target position */ this.poleTargetPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** * Gets or sets the pole target local offset */ this.poleTargetLocalOffset = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(); /** * Gets or sets the pole angle */ this.poleAngle = 0; /** * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp) */ this.slerpAmount = 1; this._bone1Quat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); this._bone1Mat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(); this._bone2Ang = Math.PI; this._maxAngle = Math.PI; this._rightHandedSystem = false; this._bendAxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right(); this._slerping = false; this._adjustRoll = 0; this._bone2 = bone; this._bone1 = bone.getParent(); if (!this._bone1) { return; } this.mesh = mesh; var bonePos = bone.getPosition(); if (bone.getAbsoluteTransform().determinant() > 0) { this._rightHandedSystem = true; this._bendAxis.x = 0; this._bendAxis.y = 0; this._bendAxis.z = -1; if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) { this._adjustRoll = Math.PI * .5; this._bendAxis.z = 1; } } if (this._bone1.length) { var boneScale1 = this._bone1.getScale(); var boneScale2 = this._bone2.getScale(); this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y; this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y; } else if (this._bone1.children[0]) { mesh.computeWorldMatrix(true); var pos1 = this._bone2.children[0].getAbsolutePosition(mesh); var pos2 = this._bone2.getAbsolutePosition(mesh); var pos3 = this._bone1.getAbsolutePosition(mesh); this._bone1Length = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(pos1, pos2); this._bone2Length = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(pos2, pos3); } this._bone1.getRotationMatrixToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, mesh, this._bone1Mat); this.maxAngle = Math.PI; if (options) { if (options.targetMesh) { this.targetMesh = options.targetMesh; this.targetMesh.computeWorldMatrix(true); } if (options.poleTargetMesh) { this.poleTargetMesh = options.poleTargetMesh; this.poleTargetMesh.computeWorldMatrix(true); } else if (options.poleTargetBone) { this.poleTargetBone = options.poleTargetBone; } else if (this._bone1.getParent()) { this.poleTargetBone = this._bone1.getParent(); } if (options.poleTargetLocalOffset) { this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset); } if (options.poleAngle) { this.poleAngle = options.poleAngle; } if (options.bendAxis) { this._bendAxis.copyFrom(options.bendAxis); } if (options.maxAngle) { this.maxAngle = options.maxAngle; } if (options.slerpAmount) { this.slerpAmount = options.slerpAmount; } } } Object.defineProperty(BoneIKController.prototype, "maxAngle", { /** * Gets or sets maximum allowed angle */ get: function () { return this._maxAngle; }, set: function (value) { this._setMaxAngle(value); }, enumerable: false, configurable: true }); BoneIKController.prototype._setMaxAngle = function (ang) { if (ang < 0) { ang = 0; } if (ang > Math.PI || ang == undefined) { ang = Math.PI; } this._maxAngle = ang; var a = this._bone1Length; var b = this._bone2Length; this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang)); }; /** * Force the controller to update the bones */ BoneIKController.prototype.update = function () { var bone1 = this._bone1; if (!bone1) { return; } var target = this.targetPosition; var poleTarget = this.poleTargetPosition; var mat1 = BoneIKController._tmpMats[0]; var mat2 = BoneIKController._tmpMats[1]; if (this.targetMesh) { target.copyFrom(this.targetMesh.getAbsolutePosition()); } if (this.poleTargetBone) { this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget); } else if (this.poleTargetMesh) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget); } var bonePos = BoneIKController._tmpVecs[0]; var zaxis = BoneIKController._tmpVecs[1]; var xaxis = BoneIKController._tmpVecs[2]; var yaxis = BoneIKController._tmpVecs[3]; var upAxis = BoneIKController._tmpVecs[4]; var _tmpQuat = BoneIKController._tmpQuat; bone1.getAbsolutePositionToRef(this.mesh, bonePos); poleTarget.subtractToRef(bonePos, upAxis); if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) { upAxis.y = 1; } else { upAxis.normalize(); } target.subtractToRef(bonePos, yaxis); yaxis.normalize(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(yaxis, upAxis, zaxis); zaxis.normalize(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(yaxis, zaxis, xaxis); xaxis.normalize(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1); var a = this._bone1Length; var b = this._bone2Length; var c = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(bonePos, target); if (this._maxReach > 0) { c = Math.min(this._maxReach, c); } var acosa = (b * b + c * c - a * a) / (2 * b * c); var acosb = (c * c + a * a - b * b) / (2 * c * a); if (acosa > 1) { acosa = 1; } if (acosb > 1) { acosb = 1; } if (acosa < -1) { acosa = -1; } if (acosb < -1) { acosb = -1; } var angA = Math.acos(acosa); var angB = Math.acos(acosb); var angC = -angA - angB; if (this._rightHandedSystem) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2); mat2.multiplyToRef(mat1, mat1); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(this._bendAxis, angB, mat2); mat2.multiplyToRef(mat1, mat1); } else { var _tmpVec = BoneIKController._tmpVecs[5]; _tmpVec.copyFrom(this._bendAxis); _tmpVec.x *= -1; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(_tmpVec, -angB, mat2); mat2.multiplyToRef(mat1, mat1); } if (this.poleAngle) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationAxisToRef(yaxis, this.poleAngle, mat2); mat1.multiplyToRef(mat2, mat1); } if (this._bone1) { if (this.slerpAmount < 1) { if (!this._slerping) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat); } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromRotationMatrixToRef(mat1, _tmpQuat); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat); angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount; this._bone1.setRotationQuaternion(this._bone1Quat, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh); this._slerping = true; } else { this._bone1.setRotationMatrix(mat1, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_1__["Space"].WORLD, this.mesh); this._bone1Mat.copyFrom(mat1); this._slerping = false; } } this._bone2.setAxisAngle(this._bendAxis, angC, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_1__["Space"].LOCAL); this._bone2Ang = angC; }; BoneIKController._tmpVecs = [_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()]; BoneIKController._tmpQuat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity(); BoneIKController._tmpMats = [_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity()]; return BoneIKController; }()); /***/ }), /***/ "./Bones/boneLookController.ts": /*!*************************************!*\ !*** ./Bones/boneLookController.ts ***! \*************************************/ /*! exports provided: BoneLookController */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return BoneLookController; }); /* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts"); /** * Class used to make a bone look toward a point in space * @see https://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller */ var BoneLookController = /** @class */ (function () { /** * Create a BoneLookController * @param mesh the mesh that the bone belongs to * @param bone the bone that will be looking to the target * @param target the target Vector3 to look at * @param options optional settings: * * maxYaw: the maximum angle the bone will yaw to * * minYaw: the minimum angle the bone will yaw to * * maxPitch: the maximum angle the bone will pitch to * * minPitch: the minimum angle the bone will yaw to * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target. * * upAxis: the up axis of the coordinate system * * upAxisSpace: the space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD. * * yawAxis: set yawAxis if the bone does not yaw on the y axis * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis * * adjustYaw: used to make an adjustment to the yaw of the bone * * adjustPitch: used to make an adjustment to the pitch of the bone * * adjustRoll: used to make an adjustment to the roll of the bone **/ function BoneLookController(mesh, bone, target, options) { /** * The up axis of the coordinate system that is used when the bone is rotated */ this.upAxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up(); /** * The space that the up axis is in - Space.BONE, Space.LOCAL (default), or Space.WORLD */ this.upAxisSpace = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].LOCAL; /** * Used to make an adjustment to the yaw of the bone */ this.adjustYaw = 0; /** * Used to make an adjustment to the pitch of the bone */ this.adjustPitch = 0; /** * Used to make an adjustment to the roll of the bone */ this.adjustRoll = 0; /** * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp) */ this.slerpAmount = 1; this._boneQuat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); this._slerping = false; this._firstFrameSkipped = false; this._fowardAxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Forward(); this.mesh = mesh; this.bone = bone; this.target = target; if (options) { if (options.adjustYaw) { this.adjustYaw = options.adjustYaw; } if (options.adjustPitch) { this.adjustPitch = options.adjustPitch; } if (options.adjustRoll) { this.adjustRoll = options.adjustRoll; } if (options.maxYaw != null) { this.maxYaw = options.maxYaw; } else { this.maxYaw = Math.PI; } if (options.minYaw != null) { this.minYaw = options.minYaw; } else { this.minYaw = -Math.PI; } if (options.maxPitch != null) { this.maxPitch = options.maxPitch; } else { this.maxPitch = Math.PI; } if (options.minPitch != null) { this.minPitch = options.minPitch; } else { this.minPitch = -Math.PI; } if (options.slerpAmount != null) { this.slerpAmount = options.slerpAmount; } if (options.upAxis != null) { this.upAxis = options.upAxis; } if (options.upAxisSpace != null) { this.upAxisSpace = options.upAxisSpace; } if (options.yawAxis != null || options.pitchAxis != null) { var newYawAxis = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Axis"].Y; var newPitchAxis = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Axis"].X; if (options.yawAxis != null) { newYawAxis = options.yawAxis.clone(); newYawAxis.normalize(); } if (options.pitchAxis != null) { newPitchAxis = options.pitchAxis.clone(); newPitchAxis.normalize(); } var newRollAxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(newPitchAxis, newYawAxis); this._transformYawPitch = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch); this._transformYawPitchInv = this._transformYawPitch.clone(); this._transformYawPitch.invert(); } } if (!bone.getParent() && this.upAxisSpace == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].BONE) { this.upAxisSpace = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].LOCAL; } } Object.defineProperty(BoneLookController.prototype, "minYaw", { /** * Gets or sets the minimum yaw angle that the bone can look to */ get: function () { return this._minYaw; }, set: function (value) { this._minYaw = value; this._minYawSin = Math.sin(value); this._minYawCos = Math.cos(value); if (this._maxYaw != null) { this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; this._yawRange = this._maxYaw - this._minYaw; } }, enumerable: false, configurable: true }); Object.defineProperty(BoneLookController.prototype, "maxYaw", { /** * Gets or sets the maximum yaw angle that the bone can look to */ get: function () { return this._maxYaw; }, set: function (value) { this._maxYaw = value; this._maxYawSin = Math.sin(value); this._maxYawCos = Math.cos(value); if (this._minYaw != null) { this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw; this._yawRange = this._maxYaw - this._minYaw; } }, enumerable: false, configurable: true }); Object.defineProperty(BoneLookController.prototype, "minPitch", { /** * Gets or sets the minimum pitch angle that the bone can look to */ get: function () { return this._minPitch; }, set: function (value) { this._minPitch = value; this._minPitchTan = Math.tan(value); }, enumerable: false, configurable: true }); Object.defineProperty(BoneLookController.prototype, "maxPitch", { /** * Gets or sets the maximum pitch angle that the bone can look to */ get: function () { return this._maxPitch; }, set: function (value) { this._maxPitch = value; this._maxPitchTan = Math.tan(value); }, enumerable: false, configurable: true }); /** * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()) */ BoneLookController.prototype.update = function () { //skip the first frame when slerping so that the mesh rotation is correct if (this.slerpAmount < 1 && !this._firstFrameSkipped) { this._firstFrameSkipped = true; return; } var bone = this.bone; var bonePos = BoneLookController._tmpVecs[0]; bone.getAbsolutePositionToRef(this.mesh, bonePos); var target = this.target; var _tmpMat1 = BoneLookController._tmpMats[0]; var _tmpMat2 = BoneLookController._tmpMats[1]; var mesh = this.mesh; var parentBone = bone.getParent(); var upAxis = BoneLookController._tmpVecs[1]; upAxis.copyFrom(this.upAxis); if (this.upAxisSpace == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].BONE && parentBone) { if (this._transformYawPitch) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis); } parentBone.getDirectionToRef(upAxis, this.mesh, upAxis); } else if (this.upAxisSpace == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].LOCAL) { mesh.getDirectionToRef(upAxis, upAxis); if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) { upAxis.normalize(); } } var checkYaw = false; var checkPitch = false; if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) { checkYaw = true; } if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) { checkPitch = true; } if (checkYaw || checkPitch) { var spaceMat = BoneLookController._tmpMats[2]; var spaceMatInv = BoneLookController._tmpMats[3]; if (this.upAxisSpace == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].BONE && upAxis.y == 1 && parentBone) { parentBone.getRotationMatrixToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].WORLD, this.mesh, spaceMat); } else if (this.upAxisSpace == _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].LOCAL && upAxis.y == 1 && !parentBone) { spaceMat.copyFrom(mesh.getWorldMatrix()); } else { var forwardAxis = BoneLookController._tmpVecs[2]; forwardAxis.copyFrom(this._fowardAxis); if (this._transformYawPitch) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis); } if (parentBone) { parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis); } else { mesh.getDirectionToRef(forwardAxis, forwardAxis); } var rightAxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(upAxis, forwardAxis); rightAxis.normalize(); var forwardAxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(rightAxis, upAxis); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat); } spaceMat.invertToRef(spaceMatInv); var xzlen = null; if (checkPitch) { var localTarget = BoneLookController._tmpVecs[3]; target.subtractToRef(bonePos, localTarget); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); var pitch = Math.atan2(localTarget.y, xzlen); var newPitch = pitch; if (pitch > this._maxPitch) { localTarget.y = this._maxPitchTan * xzlen; newPitch = this._maxPitch; } else if (pitch < this._minPitch) { localTarget.y = this._minPitchTan * xzlen; newPitch = this._minPitch; } if (pitch != newPitch) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMat, localTarget); localTarget.addInPlace(bonePos); target = localTarget; } } if (checkYaw) { var localTarget = BoneLookController._tmpVecs[4]; target.subtractToRef(bonePos, localTarget); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget); var yaw = Math.atan2(localTarget.x, localTarget.z); var newYaw = yaw; if (yaw > this._maxYaw || yaw < this._minYaw) { if (xzlen == null) { xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); } if (this._yawRange > Math.PI) { if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) { localTarget.z = this._maxYawCos * xzlen; localTarget.x = this._maxYawSin * xzlen; newYaw = this._maxYaw; } else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) { localTarget.z = this._minYawCos * xzlen; localTarget.x = this._minYawSin * xzlen; newYaw = this._minYaw; } } else { if (yaw > this._maxYaw) { localTarget.z = this._maxYawCos * xzlen; localTarget.x = this._maxYawSin * xzlen; newYaw = this._maxYaw; } else if (yaw < this._minYaw) { localTarget.z = this._minYawCos * xzlen; localTarget.x = this._minYawSin * xzlen; newYaw = this._minYaw; } } } if (this._slerping && this._yawRange > Math.PI) { //are we going to be crossing into the min/max region? var boneFwd = BoneLookController._tmpVecs[8]; boneFwd.copyFrom(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Axis"].Z); if (this._transformYawPitch) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd); } var boneRotMat = BoneLookController._tmpMats[4]; this._boneQuat.toRotationMatrix(boneRotMat); this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd); var boneYaw = Math.atan2(boneFwd.x, boneFwd.z); var angBtwTar = this._getAngleBetween(boneYaw, yaw); var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint); if (angBtwTar > angBtwMidYaw) { if (xzlen == null) { xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z); } var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw); var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw); if (angBtwMin < angBtwMax) { newYaw = boneYaw + Math.PI * .75; localTarget.z = Math.cos(newYaw) * xzlen; localTarget.x = Math.sin(newYaw) * xzlen; } else { newYaw = boneYaw - Math.PI * .75; localTarget.z = Math.cos(newYaw) * xzlen; localTarget.x = Math.sin(newYaw) * xzlen; } } } if (yaw != newYaw) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(localTarget, spaceMat, localTarget); localTarget.addInPlace(bonePos); target = localTarget; } } } var zaxis = BoneLookController._tmpVecs[5]; var xaxis = BoneLookController._tmpVecs[6]; var yaxis = BoneLookController._tmpVecs[7]; var _tmpQuat = BoneLookController._tmpQuat; target.subtractToRef(bonePos, zaxis); zaxis.normalize(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(upAxis, zaxis, xaxis); xaxis.normalize(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(zaxis, xaxis, yaxis); yaxis.normalize(); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1); if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) { return; } if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) { return; } if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) { return; } if (this.adjustYaw || this.adjustPitch || this.adjustRoll) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2); _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1); } if (this.slerpAmount < 1) { if (!this._slerping) { this.bone.getRotationQuaternionToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].WORLD, this.mesh, this._boneQuat); } if (this._transformYawPitch) { this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].FromRotationMatrixToRef(_tmpMat1, _tmpQuat); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat); this.bone.setRotationQuaternion(this._boneQuat, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].WORLD, this.mesh); this._slerping = true; } else { if (this._transformYawPitch) { this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1); } this.bone.setRotationMatrix(_tmpMat1, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_2__["Space"].WORLD, this.mesh); this._slerping = false; } }; BoneLookController.prototype._getAngleDiff = function (ang1, ang2) { var angDiff = ang2 - ang1; angDiff %= Math.PI * 2; if (angDiff > Math.PI) { angDiff -= Math.PI * 2; } else if (angDiff < -Math.PI) { angDiff += Math.PI * 2; } return angDiff; }; BoneLookController.prototype._getAngleBetween = function (ang1, ang2) { ang1 %= (2 * Math.PI); ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; ang2 %= (2 * Math.PI); ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; var ab = 0; if (ang1 < ang2) { ab = ang2 - ang1; } else { ab = ang1 - ang2; } if (ab > Math.PI) { ab = Math.PI * 2 - ab; } return ab; }; BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) { ang %= (2 * Math.PI); ang = (ang < 0) ? ang + (2 * Math.PI) : ang; ang1 %= (2 * Math.PI); ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1; ang2 %= (2 * Math.PI); ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2; if (ang1 < ang2) { if (ang > ang1 && ang < ang2) { return true; } } else { if (ang > ang2 && ang < ang1) { return true; } } return false; }; BoneLookController._tmpVecs = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(10, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero); BoneLookController._tmpQuat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].Identity(); BoneLookController._tmpMats = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(5, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity); return BoneLookController; }()); /***/ }), /***/ "./Bones/index.ts": /*!************************!*\ !*** ./Bones/index.ts ***! \************************/ /*! exports provided: Bone, BoneIKController, BoneLookController, Skeleton */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _bone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bone */ "./Bones/bone.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"]; }); /* harmony import */ var _boneIKController__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boneIKController */ "./Bones/boneIKController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return _boneIKController__WEBPACK_IMPORTED_MODULE_1__["BoneIKController"]; }); /* harmony import */ var _boneLookController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boneLookController */ "./Bones/boneLookController.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return _boneLookController__WEBPACK_IMPORTED_MODULE_2__["BoneLookController"]; }); /* harmony import */ var _skeleton__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./skeleton */ "./Bones/skeleton.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return _skeleton__WEBPACK_IMPORTED_MODULE_3__["Skeleton"]; }); /***/ }), /***/ "./Bones/skeleton.ts": /*!***************************!*\ !*** ./Bones/skeleton.ts ***! \***************************/ /*! exports provided: Skeleton */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return Skeleton; }); /* harmony import */ var _bone__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./bone */ "./Bones/bone.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/rawTexture */ "./Materials/Textures/rawTexture.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Animations/animation */ "./Animations/animation.ts"); /* harmony import */ var _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Animations/animationRange */ "./Animations/animationRange.ts"); /* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts"); /* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/deepCopier */ "./Misc/deepCopier.ts"); /** * Class used to handle skinning animations * @see https://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons */ var Skeleton = /** @class */ (function () { /** * Creates a new skeleton * @param name defines the skeleton name * @param id defines the skeleton Id * @param scene defines the hosting scene */ function Skeleton( /** defines the skeleton name */ name, /** defines the skeleton Id */ id, scene) { this.name = name; this.id = id; /** * Defines the list of child bones */ this.bones = new Array(); /** * Defines a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value) */ this.needInitialSkinMatrix = false; /** * Defines a mesh that override the matrix used to get the world matrix (null by default). */ this.overrideMesh = null; this._isDirty = true; this._meshesWithPoseMatrix = new Array(); this._identity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(); this._ranges = {}; this._lastAbsoluteTransformsUpdateId = -1; this._canUseTextureForBones = false; this._uniqueId = 0; /** @hidden */ this._numBonesWithLinkedTransformNode = 0; /** @hidden */ this._hasWaitingData = null; /** @hidden */ this._waitingOverrideMeshId = null; /** * Specifies if the skeleton should be serialized */ this.doNotSerialize = false; this._useTextureToStoreBoneMatrices = true; this._animationPropertiesOverride = null; // Events /** * An observable triggered before computing the skeleton's matrices */ this.onBeforeComputeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); this.bones = []; this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene; this._uniqueId = this._scene.getUniqueId(); this._scene.addSkeleton(this); //make sure it will recalculate the matrix next time prepare is called. this._isDirty = true; var engineCaps = this._scene.getEngine().getCaps(); this._canUseTextureForBones = engineCaps.textureFloat && engineCaps.maxVertexTextureImageUnits > 0; } Object.defineProperty(Skeleton.prototype, "useTextureToStoreBoneMatrices", { /** * Gets or sets a boolean indicating that bone matrices should be stored as a texture instead of using shader uniforms (default is true). * Please note that this option is not available if the hardware does not support it */ get: function () { return this._useTextureToStoreBoneMatrices; }, set: function (value) { this._useTextureToStoreBoneMatrices = value; this._markAsDirty(); }, enumerable: false, configurable: true }); Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", { /** * Gets or sets the animation properties override */ get: function () { if (!this._animationPropertiesOverride) { return this._scene.animationPropertiesOverride; } return this._animationPropertiesOverride; }, set: function (value) { this._animationPropertiesOverride = value; }, enumerable: false, configurable: true }); Object.defineProperty(Skeleton.prototype, "isUsingTextureForMatrices", { /** * Gets a boolean indicating that the skeleton effectively stores matrices into a texture */ get: function () { return this.useTextureToStoreBoneMatrices && this._canUseTextureForBones; }, enumerable: false, configurable: true }); Object.defineProperty(Skeleton.prototype, "uniqueId", { /** * Gets the unique ID of this skeleton */ get: function () { return this._uniqueId; }, enumerable: false, configurable: true }); /** * Gets the current object class name. * @return the class name */ Skeleton.prototype.getClassName = function () { return "Skeleton"; }; /** * Returns an array containing the root bones * @returns an array containing the root bones */ Skeleton.prototype.getChildren = function () { return this.bones.filter(function (b) { return !b.getParent(); }); }; // Members /** * Gets the list of transform matrices to send to shaders (one matrix per bone) * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) * @returns a Float32Array containing matrices data */ Skeleton.prototype.getTransformMatrices = function (mesh) { if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) { return mesh._bonesTransformMatrices; } if (!this._transformMatrices) { this.prepare(); } return this._transformMatrices; }; /** * Gets the list of transform matrices to send to shaders inside a texture (one matrix per bone) * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true) * @returns a raw texture containing the data */ Skeleton.prototype.getTransformMatrixTexture = function (mesh) { if (this.needInitialSkinMatrix && mesh._transformMatrixTexture) { return mesh._transformMatrixTexture; } return this._transformMatrixTexture; }; /** * Gets the current hosting scene * @returns a scene object */ Skeleton.prototype.getScene = function () { return this._scene; }; // Methods /** * Gets a string representing the current skeleton data * @param fullDetails defines a boolean indicating if we want a verbose version * @returns a string representing the current skeleton data */ Skeleton.prototype.toString = function (fullDetails) { var ret = "Name: " + this.name + ", nBones: " + this.bones.length; ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none"); if (fullDetails) { ret += ", Ranges: {"; var first = true; for (var name_1 in this._ranges) { if (first) { ret += ", "; first = false; } ret += name_1; } ret += "}"; } return ret; }; /** * Get bone's index searching by name * @param name defines bone's name to search for * @return the indice of the bone. Returns -1 if not found */ Skeleton.prototype.getBoneIndexByName = function (name) { for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) { if (this.bones[boneIndex].name === name) { return boneIndex; } } return -1; }; /** * Creater a new animation range * @param name defines the name of the range * @param from defines the start key * @param to defines the end key */ Skeleton.prototype.createAnimationRange = function (name, from, to) { // check name not already in use if (!this._ranges[name]) { this._ranges[name] = new _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, from, to); for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { this.bones[i].animations[0].createRange(name, from, to); } } } }; /** * Delete a specific animation range * @param name defines the name of the range * @param deleteFrames defines if frames must be removed as well */ Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) { if (deleteFrames === void 0) { deleteFrames = true; } for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { this.bones[i].animations[0].deleteRange(name, deleteFrames); } } this._ranges[name] = null; // said much faster than 'delete this._range[name]' }; /** * Gets a specific animation range * @param name defines the name of the range to look for * @returns the requested animation range or null if not found */ Skeleton.prototype.getAnimationRange = function (name) { return this._ranges[name] || null; }; /** * Gets the list of all animation ranges defined on this skeleton * @returns an array */ Skeleton.prototype.getAnimationRanges = function () { var animationRanges = []; var name; for (name in this._ranges) { animationRanges.push(this._ranges[name]); } return animationRanges; }; /** * Copy animation range from a source skeleton. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences * @param source defines the source skeleton * @param name defines the name of the range to copy * @param rescaleAsRequired defines if rescaling must be applied if required * @returns true if operation was successful */ Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) { if (rescaleAsRequired === void 0) { rescaleAsRequired = false; } if (this._ranges[name] || !source.getAnimationRange(name)) { return false; } var ret = true; var frameOffset = this._getHighestAnimationFrame() + 1; // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required var boneDict = {}; var sourceBones = source.bones; var nBones; var i; for (i = 0, nBones = sourceBones.length; i < nBones; i++) { boneDict[sourceBones[i].name] = sourceBones[i]; } if (this.bones.length !== sourceBones.length) { _Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length); ret = false; } var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null; for (i = 0, nBones = this.bones.length; i < nBones; i++) { var boneName = this.bones[i].name; var sourceBone = boneDict[boneName]; if (sourceBone) { ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio); } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("copyAnimationRange: not same rig, missing source bone " + boneName); ret = false; } } // do not call createAnimationRange(), since it also is done to bones, which was already done var range = source.getAnimationRange(name); if (range) { this._ranges[name] = new _Animations_animationRange__WEBPACK_IMPORTED_MODULE_5__["AnimationRange"](name, range.from + frameOffset, range.to + frameOffset); } return ret; }; /** * Forces the skeleton to go to rest pose */ Skeleton.prototype.returnToRest = function () { var _localScaling = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Vector3[0]; var _localRotation = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Quaternion[0]; var _localPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Vector3[1]; for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; if (bone._index !== -1) { bone.returnToRest(); if (bone._linkedTransformNode) { bone.getRestPose().decompose(_localScaling, _localRotation, _localPosition); bone._linkedTransformNode.position = _localPosition.clone(); bone._linkedTransformNode.rotationQuaternion = _localRotation.clone(); bone._linkedTransformNode.scaling = _localScaling.clone(); } } } }; Skeleton.prototype._getHighestAnimationFrame = function () { var ret = 0; for (var i = 0, nBones = this.bones.length; i < nBones; i++) { if (this.bones[i].animations[0]) { var highest = this.bones[i].animations[0].getHighestFrame(); if (ret < highest) { ret = highest; } } } return ret; }; /** * Begin a specific animation range * @param name defines the name of the range to start * @param loop defines if looping must be turned on (false by default) * @param speedRatio defines the speed ratio to apply (1 by default) * @param onAnimationEnd defines a callback which will be called when animation will end * @returns a new animatable */ Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) { var range = this.getAnimationRange(name); if (!range) { return null; } return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd); }; /** * Convert the keyframes for a range of animation on a skeleton to be relative to a given reference frame. * @param skeleton defines the Skeleton containing the animation range to convert * @param referenceFrame defines the frame that keyframes in the range will be relative to * @param range defines the name of the AnimationRange belonging to the Skeleton to convert * @returns the original skeleton */ Skeleton.MakeAnimationAdditive = function (skeleton, referenceFrame, range) { if (referenceFrame === void 0) { referenceFrame = 0; } var rangeValue = skeleton.getAnimationRange(name); // We can't make a range additive if it doesn't exist if (!rangeValue) { return null; } // Find any current scene-level animatable belonging to the target that matches the range var sceneAnimatables = skeleton._scene.getAllAnimatablesByTarget(skeleton); var rangeAnimatable = null; for (var index = 0; index < sceneAnimatables.length; index++) { var sceneAnimatable = sceneAnimatables[index]; if (sceneAnimatable.fromFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.from) && sceneAnimatable.toFrame === (rangeValue === null || rangeValue === void 0 ? void 0 : rangeValue.to)) { rangeAnimatable = sceneAnimatable; break; } } // Convert the animations belonging to the skeleton to additive keyframes var animatables = skeleton.getAnimatables(); for (var index = 0; index < animatables.length; index++) { var animatable = animatables[index]; var animations = animatable.animations; if (!animations) { continue; } for (var animIndex = 0; animIndex < animations.length; animIndex++) { _Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].MakeAnimationAdditive(animations[animIndex], referenceFrame, range); } } // Mark the scene-level animatable as additive if (rangeAnimatable) { rangeAnimatable.isAdditive = true; } return skeleton; }; /** @hidden */ Skeleton.prototype._markAsDirty = function () { this._isDirty = true; }; /** @hidden */ Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) { this._meshesWithPoseMatrix.push(mesh); }; /** @hidden */ Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) { var index = this._meshesWithPoseMatrix.indexOf(mesh); if (index > -1) { this._meshesWithPoseMatrix.splice(index, 1); } }; Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) { this.onBeforeComputeObservable.notifyObservers(this); for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; bone._childUpdateId++; var parentBone = bone.getParent(); if (parentBone) { bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix()); } else { if (initialSkinMatrix) { bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix()); } else { bone.getWorldMatrix().copyFrom(bone.getLocalMatrix()); } } if (bone._index !== -1) { var mappedIndex = bone._index === null ? index : bone._index; bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16); } } this._identity.copyToArray(targetMatrix, this.bones.length * 16); }; /** * Build all resources required to render a skeleton */ Skeleton.prototype.prepare = function () { // Update the local matrix of bones with linked transform nodes. if (this._numBonesWithLinkedTransformNode > 0) { for (var _i = 0, _a = this.bones; _i < _a.length; _i++) { var bone_1 = _a[_i]; if (bone_1._linkedTransformNode) { // Computing the world matrix also computes the local matrix. bone_1._linkedTransformNode.computeWorldMatrix(); bone_1._matrix = bone_1._linkedTransformNode._localMatrix; bone_1.markAsDirty(); } } } if (!this._isDirty) { return; } if (this.needInitialSkinMatrix) { for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) { var mesh = this._meshesWithPoseMatrix[index]; var poseMatrix = mesh.getPoseMatrix(); if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) { mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1)); } if (this._synchronizedWithMesh !== mesh) { this._synchronizedWithMesh = mesh; // Prepare bones for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) { var bone = this.bones[boneIndex]; if (!bone.getParent()) { var matrix = bone.getBaseMatrix(); matrix.multiplyToRef(poseMatrix, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Matrix[1]); bone._updateDifferenceMatrix(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Matrix[1]); } } if (this.isUsingTextureForMatrices) { var textureWidth = (this.bones.length + 1) * 4; if (!mesh._transformMatrixTexture || mesh._transformMatrixTexture.getSize().width !== textureWidth) { if (mesh._transformMatrixTexture) { mesh._transformMatrixTexture.dispose(); } mesh._transformMatrixTexture = _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__["RawTexture"].CreateRGBATexture(mesh._bonesTransformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT); } } } this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix); if (this.isUsingTextureForMatrices && mesh._transformMatrixTexture) { mesh._transformMatrixTexture.update(mesh._bonesTransformMatrices); } } } else { if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) { this._transformMatrices = new Float32Array(16 * (this.bones.length + 1)); if (this.isUsingTextureForMatrices) { if (this._transformMatrixTexture) { this._transformMatrixTexture.dispose(); } this._transformMatrixTexture = _Materials_Textures_rawTexture__WEBPACK_IMPORTED_MODULE_3__["RawTexture"].CreateRGBATexture(this._transformMatrices, (this.bones.length + 1) * 4, 1, this._scene, false, false, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE, _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT); } } this._computeTransformMatrices(this._transformMatrices, null); if (this.isUsingTextureForMatrices && this._transformMatrixTexture) { this._transformMatrixTexture.update(this._transformMatrices); } } this._isDirty = false; this._scene._activeBones.addCount(this.bones.length, false); }; /** * Gets the list of animatables currently running for this skeleton * @returns an array of animatables */ Skeleton.prototype.getAnimatables = function () { if (!this._animatables || this._animatables.length !== this.bones.length) { this._animatables = []; for (var index = 0; index < this.bones.length; index++) { this._animatables.push(this.bones[index]); } } return this._animatables; }; /** * Clone the current skeleton * @param name defines the name of the new skeleton * @param id defines the id of the new skeleton * @returns the new skeleton */ Skeleton.prototype.clone = function (name, id) { var result = new Skeleton(name, id || name, this._scene); result.needInitialSkinMatrix = this.needInitialSkinMatrix; result.overrideMesh = this.overrideMesh; for (var index = 0; index < this.bones.length; index++) { var source = this.bones[index]; var parentBone = null; var parent_1 = source.getParent(); if (parent_1) { var parentIndex = this.bones.indexOf(parent_1); parentBone = result.bones[parentIndex]; } var bone = new _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"](source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone()); bone._index = source._index; if (source._linkedTransformNode) { bone.linkTransformNode(source._linkedTransformNode); } _Misc_deepCopier__WEBPACK_IMPORTED_MODULE_9__["DeepCopier"].DeepCopy(source.animations, bone.animations); } if (this._ranges) { result._ranges = {}; for (var rangeName in this._ranges) { var range = this._ranges[rangeName]; if (range) { result._ranges[rangeName] = range.clone(); } } } this._isDirty = true; return result; }; /** * Enable animation blending for this skeleton * @param blendingSpeed defines the blending speed to apply * @see https://doc.babylonjs.com/babylon101/animations#animation-blending */ Skeleton.prototype.enableBlending = function (blendingSpeed) { if (blendingSpeed === void 0) { blendingSpeed = 0.01; } this.bones.forEach(function (bone) { bone.animations.forEach(function (animation) { animation.enableBlending = true; animation.blendingSpeed = blendingSpeed; }); }); }; /** * Releases all resources associated with the current skeleton */ Skeleton.prototype.dispose = function () { this._meshesWithPoseMatrix = []; // Animations this.getScene().stopAnimation(this); // Remove from scene this.getScene().removeSkeleton(this); if (this._transformMatrixTexture) { this._transformMatrixTexture.dispose(); this._transformMatrixTexture = null; } }; /** * Serialize the skeleton in a JSON object * @returns a JSON object */ Skeleton.prototype.serialize = function () { var _a, _b; var serializationObject = {}; serializationObject.name = this.name; serializationObject.id = this.id; if (this.dimensionsAtRest) { serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray(); } serializationObject.bones = []; serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix; serializationObject.overrideMeshId = (_a = this.overrideMesh) === null || _a === void 0 ? void 0 : _a.id; for (var index = 0; index < this.bones.length; index++) { var bone = this.bones[index]; var parent_2 = bone.getParent(); var serializedBone = { parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1, index: bone.getIndex(), name: bone.name, matrix: bone.getBaseMatrix().toArray(), rest: bone.getRestPose().toArray(), linkedTransformNodeId: (_b = bone.getTransformNode()) === null || _b === void 0 ? void 0 : _b.id }; serializationObject.bones.push(serializedBone); if (bone.length) { serializedBone.length = bone.length; } if (bone.metadata) { serializedBone.metadata = bone.metadata; } if (bone.animations && bone.animations.length > 0) { serializedBone.animation = bone.animations[0].serialize(); } serializationObject.ranges = []; for (var name in this._ranges) { var source = this._ranges[name]; if (!source) { continue; } var range = {}; range.name = name; range.from = source.from; range.to = source.to; serializationObject.ranges.push(range); } } return serializationObject; }; /** * Creates a new skeleton from serialized data * @param parsedSkeleton defines the serialized data * @param scene defines the hosting scene * @returns a new skeleton */ Skeleton.Parse = function (parsedSkeleton, scene) { var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene); if (parsedSkeleton.dimensionsAtRest) { skeleton.dimensionsAtRest = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedSkeleton.dimensionsAtRest); } skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix; if (parsedSkeleton.overrideMeshId) { skeleton._hasWaitingData = true; skeleton._waitingOverrideMeshId = parsedSkeleton.overrideMeshId; } var index; for (index = 0; index < parsedSkeleton.bones.length; index++) { var parsedBone = parsedSkeleton.bones[index]; var parsedBoneIndex = parsedSkeleton.bones[index].index; var parentBone = null; if (parsedBone.parentBoneIndex > -1) { parentBone = skeleton.bones[parsedBone.parentBoneIndex]; } var rest = parsedBone.rest ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromArray(parsedBone.rest) : null; var bone = new _bone__WEBPACK_IMPORTED_MODULE_0__["Bone"](parsedBone.name, skeleton, parentBone, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromArray(parsedBone.matrix), rest, null, parsedBoneIndex); if (parsedBone.id !== undefined && parsedBone.id !== null) { bone.id = parsedBone.id; } if (parsedBone.length) { bone.length = parsedBone.length; } if (parsedBone.metadata) { bone.metadata = parsedBone.metadata; } if (parsedBone.animation) { bone.animations.push(_Animations_animation__WEBPACK_IMPORTED_MODULE_4__["Animation"].Parse(parsedBone.animation)); } if (parsedBone.linkedTransformNodeId !== undefined && parsedBone.linkedTransformNodeId !== null) { skeleton._hasWaitingData = true; bone._waitingTransformNodeId = parsedBone.linkedTransformNodeId; } } // placed after bones, so createAnimationRange can cascade down if (parsedSkeleton.ranges) { for (index = 0; index < parsedSkeleton.ranges.length; index++) { var data = parsedSkeleton.ranges[index]; skeleton.createAnimationRange(data.name, data.from, data.to); } } return skeleton; }; /** * Compute all node absolute transforms * @param forceUpdate defines if computation must be done even if cache is up to date */ Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) { if (forceUpdate === void 0) { forceUpdate = false; } var renderId = this._scene.getRenderId(); if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) { this.bones[0].computeAbsoluteTransforms(); this._lastAbsoluteTransformsUpdateId = renderId; } }; /** * Gets the root pose matrix * @returns a matrix */ Skeleton.prototype.getPoseMatrix = function () { var poseMatrix = null; if (this._meshesWithPoseMatrix.length > 0) { poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix(); } return poseMatrix; }; /** * Sorts bones per internal index */ Skeleton.prototype.sortBones = function () { var bones = new Array(); var visited = new Array(this.bones.length); for (var index = 0; index < this.bones.length; index++) { this._sortBones(index, bones, visited); } this.bones = bones; }; Skeleton.prototype._sortBones = function (index, bones, visited) { if (visited[index]) { return; } visited[index] = true; var bone = this.bones[index]; if (bone._index === undefined) { bone._index = index; } var parentBone = bone.getParent(); if (parentBone) { this._sortBones(this.bones.indexOf(parentBone), bones, visited); } bones.push(bone); }; return Skeleton; }()); /***/ }), /***/ "./Cameras/Inputs/BaseCameraPointersInput.ts": /*!***************************************************!*\ !*** ./Cameras/Inputs/BaseCameraPointersInput.ts ***! \***************************************************/ /*! exports provided: BaseCameraPointersInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BaseCameraPointersInput", function() { return BaseCameraPointersInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Base class for Camera Pointer Inputs. * See FollowCameraPointersInput in src/Cameras/Inputs/followCameraPointersInput.ts * for example usage. */ var BaseCameraPointersInput = /** @class */ (function () { function BaseCameraPointersInput() { /** * Defines the buttons associated with the input to handle camera move. */ this.buttons = [0, 1, 2]; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ BaseCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var engine = this.camera.getEngine(); var previousPinchSquaredDistance = 0; var previousMultiTouchPanPosition = null; this.pointA = null; this.pointB = null; this._altKey = false; this._ctrlKey = false; this._metaKey = false; this._shiftKey = false; this._buttonsPressed = 0; this._pointerInput = function (p, s) { var evt = p.event; var isTouch = evt.pointerType === "touch"; if (engine.isInVRExclusivePointerMode) { return; } if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) { return; } var srcElement = (evt.srcElement || evt.target); _this._altKey = evt.altKey; _this._ctrlKey = evt.ctrlKey; _this._metaKey = evt.metaKey; _this._shiftKey = evt.shiftKey; _this._buttonsPressed = evt.buttons; if (engine.isPointerLock) { var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0; var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0; _this.onTouch(null, offsetX, offsetY); _this.pointA = null; _this.pointB = null; } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN && srcElement) { try { srcElement.setPointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. Execution will continue. } if (_this.pointA === null) { _this.pointA = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType }; } else if (_this.pointB === null) { _this.pointB = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType }; } _this.onButtonDown(evt); if (!noPreventDefault) { evt.preventDefault(); element.focus(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOUBLETAP) { _this.onDoubleTap(evt.pointerType); } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP && srcElement) { try { srcElement.releasePointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. } if (!isTouch) { _this.pointB = null; // Mouse and pen are mono pointer } //would be better to use pointers.remove(evt.pointerId) for multitouch gestures, //but emptying completely pointers collection is required to fix a bug on iPhone : //when changing orientation while pinching camera, //one pointer stay pressed forever if we don't release all pointers //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected if (engine._badOS) { _this.pointA = _this.pointB = null; } else { //only remove the impacted pointer in case of multitouch allowing on most //platforms switching from rotate to zoom and pan seamlessly. if (_this.pointB && _this.pointA && _this.pointA.pointerId == evt.pointerId) { _this.pointA = _this.pointB; _this.pointB = null; } else if (_this.pointA && _this.pointB && _this.pointB.pointerId == evt.pointerId) { _this.pointB = null; } else { _this.pointA = _this.pointB = null; } } if (previousPinchSquaredDistance !== 0 || previousMultiTouchPanPosition) { // Previous pinch data is populated but a button has been lifted // so pinch has ended. _this.onMultiTouch(_this.pointA, _this.pointB, previousPinchSquaredDistance, 0, // pinchSquaredDistance previousMultiTouchPanPosition, null // multiTouchPanPosition ); previousPinchSquaredDistance = 0; previousMultiTouchPanPosition = null; } _this.onButtonUp(evt); if (!noPreventDefault) { evt.preventDefault(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { if (!noPreventDefault) { evt.preventDefault(); } // One button down if (_this.pointA && _this.pointB === null) { var offsetX = evt.clientX - _this.pointA.x; var offsetY = evt.clientY - _this.pointA.y; _this.onTouch(_this.pointA, offsetX, offsetY); _this.pointA.x = evt.clientX; _this.pointA.y = evt.clientY; } // Two buttons down: pinch else if (_this.pointA && _this.pointB) { var ed = (_this.pointA.pointerId === evt.pointerId) ? _this.pointA : _this.pointB; ed.x = evt.clientX; ed.y = evt.clientY; var distX = _this.pointA.x - _this.pointB.x; var distY = _this.pointA.y - _this.pointB.y; var pinchSquaredDistance = (distX * distX) + (distY * distY); var multiTouchPanPosition = { x: (_this.pointA.x + _this.pointB.x) / 2, y: (_this.pointA.y + _this.pointB.y) / 2, pointerId: evt.pointerId, type: p.type }; _this.onMultiTouch(_this.pointA, _this.pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition); previousMultiTouchPanPosition = multiTouchPanPosition; previousPinchSquaredDistance = pinchSquaredDistance; } } }; this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); this._onLostFocus = function () { _this.pointA = _this.pointB = null; previousPinchSquaredDistance = 0; previousMultiTouchPanPosition = null; _this.onLostFocus(); }; element.addEventListener("contextmenu", this.onContextMenu.bind(this), false); var hostWindow = this.camera.getScene().getEngine().getHostWindow(); if (hostWindow) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].RegisterTopRootEvents(hostWindow, [ { name: "blur", handler: this._onLostFocus } ]); } }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ BaseCameraPointersInput.prototype.detachControl = function (element) { if (this._onLostFocus) { var hostWindow = this.camera.getScene().getEngine().getHostWindow(); if (hostWindow) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].UnregisterTopRootEvents(hostWindow, [ { name: "blur", handler: this._onLostFocus } ]); } } if (element && this._observer) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; if (this.onContextMenu) { element.removeEventListener("contextmenu", this.onContextMenu); } this._onLostFocus = null; } this._altKey = false; this._ctrlKey = false; this._metaKey = false; this._shiftKey = false; this._buttonsPressed = 0; }; /** * Gets the class name of the current input. * @returns the class name */ BaseCameraPointersInput.prototype.getClassName = function () { return "BaseCameraPointersInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ BaseCameraPointersInput.prototype.getSimpleName = function () { return "pointers"; }; /** * Called on pointer POINTERDOUBLETAP event. * Override this method to provide functionality on POINTERDOUBLETAP event. */ BaseCameraPointersInput.prototype.onDoubleTap = function (type) { }; /** * Called on pointer POINTERMOVE event if only a single touch is active. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onTouch = function (point, offsetX, offsetY) { }; /** * Called on pointer POINTERMOVE event if multiple touches are active. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { }; /** * Called on JS contextmenu event. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onContextMenu = function (evt) { evt.preventDefault(); }; /** * Called each time a new POINTERDOWN event occurs. Ie, for each button * press. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onButtonDown = function (evt) { }; /** * Called each time a new POINTERUP event occurs. Ie, for each button * release. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onButtonUp = function (evt) { }; /** * Called when window becomes inactive. * Override this method to provide functionality. */ BaseCameraPointersInput.prototype.onLostFocus = function () { }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], BaseCameraPointersInput.prototype, "buttons", void 0); return BaseCameraPointersInput; }()); /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts": /*!*******************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraGamepadInput.ts ***! \*******************************************************/ /*! exports provided: ArcRotateCameraGamepadInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return ArcRotateCameraGamepadInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /** * Manage the gamepad inputs to control an arc rotate camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraGamepadInput = /** @class */ (function () { function ArcRotateCameraGamepadInput() { /** * Defines the gamepad rotation sensiblity. * This is the threshold from when rotation starts to be accounted for to prevent jittering. */ this.gamepadRotationSensibility = 80; /** * Defines the gamepad move sensiblity. * This is the threshold from when moving starts to be accounted for for to prevent jittering. */ this.gamepadMoveSensibility = 40; this._yAxisScale = 1.0; } Object.defineProperty(ArcRotateCameraGamepadInput.prototype, "invertYAxis", { /** * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted */ get: function () { return this._yAxisScale !== 1.0; }, set: function (value) { this._yAxisScale = value ? -1.0 : 1.0; }, enumerable: false, configurable: true }); /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var manager = this.camera.getScene().gamepadManager; this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].POSE_ENABLED) { // prioritize XBOX gamepads. if (!_this.gamepad || gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].XBOX) { _this.gamepad = gamepad; } } }); this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (_this.gamepad === gamepad) { _this.gamepad = null; } }); this.gamepad = manager.getGamepadByType(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_3__["Gamepad"].XBOX); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraGamepadInput.prototype.detachControl = function (element) { this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); this.gamepad = null; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ ArcRotateCameraGamepadInput.prototype.checkInputs = function () { if (this.gamepad) { var camera = this.camera; var RSValues = this.gamepad.rightStick; if (RSValues) { if (RSValues.x != 0) { var normalizedRX = RSValues.x / this.gamepadRotationSensibility; if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) { camera.inertialAlphaOffset += normalizedRX; } } if (RSValues.y != 0) { var normalizedRY = (RSValues.y / this.gamepadRotationSensibility) * this._yAxisScale; if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) { camera.inertialBetaOffset += normalizedRY; } } } var LSValues = this.gamepad.leftStick; if (LSValues && LSValues.y != 0) { var normalizedLY = LSValues.y / this.gamepadMoveSensibility; if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) { this.camera.inertialRadiusOffset -= normalizedLY; } } } }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraGamepadInput.prototype.getClassName = function () { return "ArcRotateCameraGamepadInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraGamepadInput.prototype.getSimpleName = function () { return "gamepad"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); return ArcRotateCameraGamepadInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts": /*!************************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts ***! \************************************************************/ /*! exports provided: ArcRotateCameraKeyboardMoveInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return ArcRotateCameraKeyboardMoveInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /** * Manage the keyboard inputs to control the movement of an arc rotate camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () { function ArcRotateCameraKeyboardMoveInput() { /** * Defines the list of key codes associated with the up action (increase alpha) */ this.keysUp = [38]; /** * Defines the list of key codes associated with the down action (decrease alpha) */ this.keysDown = [40]; /** * Defines the list of key codes associated with the left action (increase beta) */ this.keysLeft = [37]; /** * Defines the list of key codes associated with the right action (decrease beta) */ this.keysRight = [39]; /** * Defines the list of key codes associated with the reset action. * Those keys reset the camera to its last stored state (with the method camera.storeState()) */ this.keysReset = [220]; /** * Defines the panning sensibility of the inputs. * (How fast is the camera panning) */ this.panningSensibility = 50.0; /** * Defines the zooming sensibility of the inputs. * (How fast is the camera zooming) */ this.zoomingSensibility = 25.0; /** * Defines whether maintaining the alt key down switch the movement mode from * orientation to zoom. */ this.useAltToZoom = true; /** * Rotation speed of the camera */ this.angularSpeed = 0.01; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (!evt.metaKey) { if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { _this._ctrlPressed = evt.ctrlKey; _this._altPressed = evt.altKey; if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysReset.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } else { if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysReset.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () { if (this._onKeyboardObserver) { var camera = this.camera; for (var index = 0; index < this._keys.length; index++) { var keyCode = this._keys[index]; if (this.keysLeft.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningX -= 1 / this.panningSensibility; } else { camera.inertialAlphaOffset -= this.angularSpeed; } } else if (this.keysUp.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningY += 1 / this.panningSensibility; } else if (this._altPressed && this.useAltToZoom) { camera.inertialRadiusOffset += 1 / this.zoomingSensibility; } else { camera.inertialBetaOffset -= this.angularSpeed; } } else if (this.keysRight.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningX += 1 / this.panningSensibility; } else { camera.inertialAlphaOffset += this.angularSpeed; } } else if (this.keysDown.indexOf(keyCode) !== -1) { if (this._ctrlPressed && this.camera._useCtrlForPanning) { camera.inertialPanningY -= 1 / this.panningSensibility; } else if (this._altPressed && this.useAltToZoom) { camera.inertialRadiusOffset -= 1 / this.zoomingSensibility; } else { camera.inertialBetaOffset += this.angularSpeed; } } else if (this.keysReset.indexOf(keyCode) !== -1) { if (camera.useInputToRestoreState) { camera.restoreState(); } } } } }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () { return "ArcRotateCameraKeyboardMoveInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0); return ArcRotateCameraKeyboardMoveInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts": /*!**********************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts ***! \**********************************************************/ /*! exports provided: ArcRotateCameraMouseWheelInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return ArcRotateCameraMouseWheelInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.scalar */ "./Maths/math.scalar.ts"); /** * Manage the mouse wheel inputs to control an arc rotate camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraMouseWheelInput = /** @class */ (function () { function ArcRotateCameraMouseWheelInput() { /** * Gets or Set the mouse wheel precision or how fast is the camera zooming. */ this.wheelPrecision = 3.0; /** * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. * It defines the percentage of current camera.radius to use as delta when wheel is used. */ this.wheelDeltaPercentage = 0; } ArcRotateCameraMouseWheelInput.prototype.computeDeltaFromMouseWheelLegacyEvent = function (mouseWheelDelta, radius) { var delta = 0; var wheelDelta = (mouseWheelDelta * 0.01 * this.wheelDeltaPercentage) * radius; if (mouseWheelDelta > 0) { delta = wheelDelta / (1.0 + this.wheelDeltaPercentage); } else { delta = wheelDelta * (1.0 + this.wheelDeltaPercentage); } return delta; }; /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this._wheel = function (p, s) { //sanity check - this should be a PointerWheel event. if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL) { return; } var event = p.event; var delta = 0; var mouseWheelLegacyEvent = event; var wheelDelta = 0; if (mouseWheelLegacyEvent.wheelDelta) { wheelDelta = mouseWheelLegacyEvent.wheelDelta; } else { wheelDelta = -(event.deltaY || event.detail) * 60; } if (_this.wheelDeltaPercentage) { delta = _this.computeDeltaFromMouseWheelLegacyEvent(wheelDelta, _this.camera.radius); // If zooming in, estimate the target radius and use that to compute the delta for inertia // this will stop multiple scroll events zooming in from adding too much inertia if (delta > 0) { var estimatedTargetRadius = _this.camera.radius; var targetInertia = _this.camera.inertialRadiusOffset + delta; for (var i = 0; i < 20 && Math.abs(targetInertia) > 0.001; i++) { estimatedTargetRadius -= targetInertia; targetInertia *= _this.camera.inertia; } estimatedTargetRadius = _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_4__["Scalar"].Clamp(estimatedTargetRadius, 0, Number.MAX_VALUE); delta = _this.computeDeltaFromMouseWheelLegacyEvent(wheelDelta, estimatedTargetRadius); } } else { delta = wheelDelta / (_this.wheelPrecision * 40); } if (delta) { _this.camera.inertialRadiusOffset += delta; } if (event.preventDefault) { if (!noPreventDefault) { event.preventDefault(); } } }; this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; this._wheel = null; } }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraMouseWheelInput.prototype.getClassName = function () { return "ArcRotateCameraMouseWheelInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () { return "mousewheel"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); return ArcRotateCameraMouseWheelInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraPointersInput.ts": /*!********************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraPointersInput.ts ***! \********************************************************/ /*! exports provided: ArcRotateCameraPointersInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return ArcRotateCameraPointersInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/Inputs/BaseCameraPointersInput */ "./Cameras/Inputs/BaseCameraPointersInput.ts"); /** * Manage the pointers inputs to control an arc rotate camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraPointersInput = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ArcRotateCameraPointersInput, _super); function ArcRotateCameraPointersInput() { var _this = _super !== null && _super.apply(this, arguments) || this; /** * Defines the buttons associated with the input to handle camera move. */ _this.buttons = [0, 1, 2]; /** * Defines the pointer angular sensibility along the X axis or how fast is * the camera rotating. */ _this.angularSensibilityX = 1000.0; /** * Defines the pointer angular sensibility along the Y axis or how fast is * the camera rotating. */ _this.angularSensibilityY = 1000.0; /** * Defines the pointer pinch precision or how fast is the camera zooming. */ _this.pinchPrecision = 12.0; /** * pinchDeltaPercentage will be used instead of pinchPrecision if different * from 0. * It defines the percentage of current camera.radius to use as delta when * pinch zoom is used. */ _this.pinchDeltaPercentage = 0; /** * When useNaturalPinchZoom is true, multi touch zoom will zoom in such * that any object in the plane at the camera's target point will scale * perfectly with finger motion. * Overrides pinchDeltaPercentage and pinchPrecision. */ _this.useNaturalPinchZoom = false; /** * Defines the pointer panning sensibility or how fast is the camera moving. */ _this.panningSensibility = 1000.0; /** * Defines whether panning (2 fingers swipe) is enabled through multitouch. */ _this.multiTouchPanning = true; /** * Defines whether panning is enabled for both pan (2 fingers swipe) and * zoom (pinch) through multitouch. */ _this.multiTouchPanAndZoom = true; /** * Revers pinch action direction. */ _this.pinchInwards = true; _this._isPanClick = false; _this._twoFingerActivityCount = 0; _this._isPinching = false; return _this; } /** * Gets the class name of the current input. * @returns the class name */ ArcRotateCameraPointersInput.prototype.getClassName = function () { return "ArcRotateCameraPointersInput"; }; /** * Called on pointer POINTERMOVE event if only a single touch is active. */ ArcRotateCameraPointersInput.prototype.onTouch = function (point, offsetX, offsetY) { if (this.panningSensibility !== 0 && ((this._ctrlKey && this.camera._useCtrlForPanning) || this._isPanClick)) { this.camera.inertialPanningX += -offsetX / this.panningSensibility; this.camera.inertialPanningY += offsetY / this.panningSensibility; } else { this.camera.inertialAlphaOffset -= offsetX / this.angularSensibilityX; this.camera.inertialBetaOffset -= offsetY / this.angularSensibilityY; } }; /** * Called on pointer POINTERDOUBLETAP event. */ ArcRotateCameraPointersInput.prototype.onDoubleTap = function (type) { if (this.camera.useInputToRestoreState) { this.camera.restoreState(); } }; /** * Called on pointer POINTERMOVE event if multiple touches are active. */ ArcRotateCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { // First time this method is called for new pinch. // Next time this is called there will be a // previousPinchSquaredDistance and pinchSquaredDistance to compare. return; } if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { // Last time this method is called at the end of a pinch. return; } var direction = this.pinchInwards ? 1 : -1; if (this.multiTouchPanAndZoom) { if (this.useNaturalPinchZoom) { this.camera.radius = this.camera.radius * Math.sqrt(previousPinchSquaredDistance) / Math.sqrt(pinchSquaredDistance); } else if (this.pinchDeltaPercentage) { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * this.camera.radius * this.pinchDeltaPercentage; } else { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * direction * (this.angularSensibilityX + this.angularSensibilityY) / 2); } if (this.panningSensibility !== 0 && previousMultiTouchPanPosition && multiTouchPanPosition) { var moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; var moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; } } else { this._twoFingerActivityCount++; var previousPinchDistance = Math.sqrt(previousPinchSquaredDistance); var pinchDistance = Math.sqrt(pinchSquaredDistance); if (this._isPinching || (this._twoFingerActivityCount < 20 && Math.abs(pinchDistance - previousPinchDistance) > this.camera.pinchToPanMaxDistance)) { // Since pinch has not been active long, assume we intend to zoom. if (this.pinchDeltaPercentage) { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) * 0.001 * this.camera.radius * this.pinchDeltaPercentage; } else { this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * direction * (this.angularSensibilityX + this.angularSensibilityY) / 2); } // Since we are pinching, remain pinching on next iteration. this._isPinching = true; } else { // Pause between pinch starting and moving implies not a zoom event. // Pan instead. if (this.panningSensibility !== 0 && this.multiTouchPanning && multiTouchPanPosition && previousMultiTouchPanPosition) { var moveDeltaX = multiTouchPanPosition.x - previousMultiTouchPanPosition.x; var moveDeltaY = multiTouchPanPosition.y - previousMultiTouchPanPosition.y; this.camera.inertialPanningX += -moveDeltaX / this.panningSensibility; this.camera.inertialPanningY += moveDeltaY / this.panningSensibility; } } } }; /** * Called each time a new POINTERDOWN event occurs. Ie, for each button * press. */ ArcRotateCameraPointersInput.prototype.onButtonDown = function (evt) { this._isPanClick = evt.button === this.camera._panningMouseButton; }; /** * Called each time a new POINTERUP event occurs. Ie, for each button * release. */ ArcRotateCameraPointersInput.prototype.onButtonUp = function (evt) { this._twoFingerActivityCount = 0; this._isPinching = false; }; /** * Called when window becomes inactive. */ ArcRotateCameraPointersInput.prototype.onLostFocus = function () { this._isPanClick = false; this._twoFingerActivityCount = 0; this._isPinching = false; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "buttons", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "useNaturalPinchZoom", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0); return ArcRotateCameraPointersInput; }(_Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["BaseCameraPointersInput"])); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput; /***/ }), /***/ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts": /*!*******************************************************************!*\ !*** ./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts ***! \*******************************************************************/ /*! exports provided: ArcRotateCameraVRDeviceOrientationInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return ArcRotateCameraVRDeviceOrientationInput; }); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /** * Add orientation input support to the input manager. * @returns the current input manager */ _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraInputsManager"].prototype.addVRDeviceOrientation = function () { this.add(new ArcRotateCameraVRDeviceOrientationInput()); return this; }; /** * Manage the device orientation inputs (gyroscope) to control an arc rotate camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () { /** * Instantiate a new ArcRotateCameraVRDeviceOrientationInput. */ function ArcRotateCameraVRDeviceOrientationInput() { /** * Defines a correction factor applied on the alpha value retrieved from the orientation events. */ this.alphaCorrection = 1; /** * Defines a correction factor applied on the gamma value retrieved from the orientation events. */ this.gammaCorrection = 1; this._alpha = 0; this._gamma = 0; this._dirty = false; this._deviceOrientationHandler = this._onOrientationEvent.bind(this); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this.camera.attachControl(element, noPreventDefault); var hostWindow = this.camera.getScene().getEngine().getHostWindow(); if (hostWindow) { // check iOS 13+ support if (typeof (DeviceOrientationEvent) !== "undefined" && typeof DeviceOrientationEvent.requestPermission === 'function') { DeviceOrientationEvent.requestPermission() .then(function (response) { if (response === 'granted') { hostWindow.addEventListener("deviceorientation", _this._deviceOrientationHandler); } else { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Warn("Permission not granted."); } }) .catch(function (error) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Error(error); }); } else { hostWindow.addEventListener("deviceorientation", this._deviceOrientationHandler); } } }; /** @hidden */ ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) { if (evt.alpha !== null) { this._alpha = (+evt.alpha | 0) * this.alphaCorrection; } if (evt.gamma !== null) { this._gamma = (+evt.gamma | 0) * this.gammaCorrection; } this._dirty = true; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () { if (this._dirty) { this._dirty = false; if (this._gamma < 0) { this._gamma = 180 + this._gamma; } this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2; this.camera.beta = (this._gamma / 180.0 * Math.PI); } }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) { window.removeEventListener("deviceorientation", this._deviceOrientationHandler); }; /** * Gets the class name of the current intput. * @returns the class name */ ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () { return "ArcRotateCameraVRDeviceOrientationInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () { return "VRDeviceOrientation"; }; return ArcRotateCameraVRDeviceOrientationInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput; /***/ }), /***/ "./Cameras/Inputs/flyCameraKeyboardInput.ts": /*!**************************************************!*\ !*** ./Cameras/Inputs/flyCameraKeyboardInput.ts ***! \**************************************************/ /*! exports provided: FlyCameraKeyboardInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return FlyCameraKeyboardInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /** * Listen to keyboard events to control the camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FlyCameraKeyboardInput = /** @class */ (function () { function FlyCameraKeyboardInput() { /** * The list of keyboard keys used to control the forward move of the camera. */ this.keysForward = [87]; /** * The list of keyboard keys used to control the backward move of the camera. */ this.keysBackward = [83]; /** * The list of keyboard keys used to control the forward move of the camera. */ this.keysUp = [69]; /** * The list of keyboard keys used to control the backward move of the camera. */ this.keysDown = [81]; /** * The list of keyboard keys used to control the right strafe move of the camera. */ this.keysRight = [68]; /** * The list of keyboard keys used to control the left strafe move of the camera. */ this.keysLeft = [65]; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FlyCameraKeyboardInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { if (_this.keysForward.indexOf(evt.keyCode) !== -1 || _this.keysBackward.indexOf(evt.keyCode) !== -1 || _this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (!noPreventDefault) { evt.preventDefault(); } } } else { if (_this.keysForward.indexOf(evt.keyCode) !== -1 || _this.keysBackward.indexOf(evt.keyCode) !== -1 || _this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (!noPreventDefault) { evt.preventDefault(); } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FlyCameraKeyboardInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Gets the class name of the current intput. * @returns the class name */ FlyCameraKeyboardInput.prototype.getClassName = function () { return "FlyCameraKeyboardInput"; }; /** @hidden */ FlyCameraKeyboardInput.prototype._onLostFocus = function (e) { this._keys = []; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FlyCameraKeyboardInput.prototype.getSimpleName = function () { return "keyboard"; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FlyCameraKeyboardInput.prototype.checkInputs = function () { if (this._onKeyboardObserver) { var camera = this.camera; // Keyboard for (var index = 0; index < this._keys.length; index++) { var keyCode = this._keys[index]; var speed = camera._computeLocalCameraSpeed(); if (this.keysForward.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, speed); } else if (this.keysBackward.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, -speed); } else if (this.keysUp.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, speed, 0); } else if (this.keysDown.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, -speed, 0); } else if (this.keysRight.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(speed, 0, 0); } else if (this.keysLeft.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(-speed, 0, 0); } if (camera.getScene().useRightHandedSystem) { camera._localDirection.z *= -1; } camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); camera.cameraDirection.addInPlace(camera._transformedDirection); } } }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysForward", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysBackward", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysUp", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysDown", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysRight", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraKeyboardInput.prototype, "keysLeft", void 0); return FlyCameraKeyboardInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FlyCameraKeyboardInput"] = FlyCameraKeyboardInput; /***/ }), /***/ "./Cameras/Inputs/flyCameraMouseInput.ts": /*!***********************************************!*\ !*** ./Cameras/Inputs/flyCameraMouseInput.ts ***! \***********************************************/ /*! exports provided: FlyCameraMouseInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return FlyCameraMouseInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Maths/math.axis */ "./Maths/math.axis.ts"); /** * Listen to mouse events to control the camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FlyCameraMouseInput = /** @class */ (function () { /** * Listen to mouse events to control the camera. * @param touchEnabled Define if touch is enabled. (Default is true.) * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ function FlyCameraMouseInput(touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } /** * Defines the buttons associated with the input to handle camera rotation. */ this.buttons = [0, 1, 2]; /** * Assign buttons for Yaw control. */ this.buttonsYaw = [-1, 0, 1]; /** * Assign buttons for Pitch control. */ this.buttonsPitch = [-1, 0, 1]; /** * Assign buttons for Roll control. */ this.buttonsRoll = [2]; /** * Detect if any button is being pressed while mouse is moved. * -1 = Mouse locked. * 0 = Left button. * 1 = Middle Button. * 2 = Right Button. */ this.activeButton = -1; /** * Defines the pointer's angular sensibility, to control the camera rotation speed. * Higher values reduce its sensitivity. */ this.angularSensibility = 1000.0; this.previousPosition = null; } /** * Attach the mouse control to the HTML DOM element. * @param element Defines the element that listens to the input events. * @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). */ FlyCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this.element = element; this.noPreventDefault = noPreventDefault; this._observer = this.camera.getScene().onPointerObservable.add(function (p, s) { _this._pointerInput(p, s); }, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); // Correct Roll by rate, if enabled. this._rollObserver = this.camera.getScene().onBeforeRenderObservable.add(function () { if (_this.camera.rollCorrect) { _this.camera.restoreRoll(_this.camera.rollCorrect); } }); // Helper function to keep 'this'. this._mousemoveCallback = function (e) { _this._onMouseMove(e); }; element.addEventListener("mousemove", this._mousemoveCallback, false); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FlyCameraMouseInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); this.camera.getScene().onBeforeRenderObservable.remove(this._rollObserver); if (this._mousemoveCallback) { element.removeEventListener("mousemove", this._mousemoveCallback); } this._observer = null; this._rollObserver = null; this.previousPosition = null; this.noPreventDefault = undefined; } }; /** * Gets the class name of the current input. * @returns the class name. */ FlyCameraMouseInput.prototype.getClassName = function () { return "FlyCameraMouseInput"; }; /** * Get the friendly name associated with the input class. * @returns the input's friendly name. */ FlyCameraMouseInput.prototype.getSimpleName = function () { return "mouse"; }; // Track mouse movement, when the pointer is not locked. FlyCameraMouseInput.prototype._pointerInput = function (p, s) { var e = p.event; var camera = this.camera; var engine = camera.getEngine(); if (engine.isInVRExclusivePointerMode) { return; } if (!this.touchEnabled && e.pointerType === "touch") { return; } // Mouse is moved but an unknown mouse button is pressed. if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE && this.buttons.indexOf(e.button) === -1) { return; } var srcElement = (e.srcElement || e.target); // Mouse down. if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN && srcElement) { try { srcElement.setPointerCapture(e.pointerId); } catch (e) { // Nothing to do with the error. Execution continues. } this.previousPosition = { x: e.clientX, y: e.clientY }; this.activeButton = e.button; if (!this.noPreventDefault) { e.preventDefault(); this.element.focus(); } } else // Mouse up. if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP && srcElement) { try { srcElement.releasePointerCapture(e.pointerId); } catch (e) { // Nothing to do with the error. Execution continues. } this.activeButton = -1; this.previousPosition = null; if (!this.noPreventDefault) { e.preventDefault(); } } else // Mouse move. if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { if (!this.previousPosition || engine.isPointerLock) { return; } var offsetX = e.clientX - this.previousPosition.x; var offsetY = e.clientY - this.previousPosition.y; this.rotateCamera(offsetX, offsetY); this.previousPosition = { x: e.clientX, y: e.clientY }; if (!this.noPreventDefault) { e.preventDefault(); } } }; // Track mouse movement, when pointer is locked. FlyCameraMouseInput.prototype._onMouseMove = function (e) { var camera = this.camera; var engine = camera.getEngine(); if (!engine.isPointerLock || engine.isInVRExclusivePointerMode) { return; } var offsetX = e.movementX || e.mozMovementX || e.webkitMovementX || e.msMovementX || 0; var offsetY = e.movementY || e.mozMovementY || e.webkitMovementY || e.msMovementY || 0; this.rotateCamera(offsetX, offsetY); this.previousPosition = null; if (!this.noPreventDefault) { e.preventDefault(); } }; /** * Rotate camera by mouse offset. */ FlyCameraMouseInput.prototype.rotateCamera = function (offsetX, offsetY) { var _this = this; var camera = this.camera; var scene = this.camera.getScene(); if (scene.useRightHandedSystem) { offsetX *= -1; } if (camera.parent && camera.parent._getWorldMatrixDeterminant() < 0) { offsetX *= -1; } var x = offsetX / this.angularSensibility; var y = offsetY / this.angularSensibility; // Initialize to current rotation. var currentRotation = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, camera.rotation.z); var rotationChange; // Pitch. if (this.buttonsPitch.some(function (v) { return v === _this.activeButton; })) { // Apply change in Radians to vector Angle. rotationChange = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].X, y); // Apply Pitch to quaternion. currentRotation.multiplyInPlace(rotationChange); } // Yaw. if (this.buttonsYaw.some(function (v) { return v === _this.activeButton; })) { // Apply change in Radians to vector Angle. rotationChange = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].Y, x); // Apply Yaw to quaternion. currentRotation.multiplyInPlace(rotationChange); // Add Roll, if banked turning is enabled, within Roll limit. var limit = (camera.bankedTurnLimit) + camera._trackRoll; // Defaults to 90° plus manual roll. if (camera.bankedTurn && -limit < camera.rotation.z && camera.rotation.z < limit) { var bankingDelta = camera.bankedTurnMultiplier * -x; // Apply change in Radians to vector Angle. rotationChange = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].Z, bankingDelta); // Apply Yaw to quaternion. currentRotation.multiplyInPlace(rotationChange); } } // Roll. if (this.buttonsRoll.some(function (v) { return v === _this.activeButton; })) { // Apply change in Radians to vector Angle. rotationChange = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].RotationAxis(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].Z, -x); // Track Rolling. camera._trackRoll -= x; // Apply Pitch to quaternion. currentRotation.multiplyInPlace(rotationChange); } // Apply rotationQuaternion to Euler camera.rotation. currentRotation.toEulerAnglesToRef(camera.rotation); }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraMouseInput.prototype, "buttons", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FlyCameraMouseInput.prototype, "angularSensibility", void 0); return FlyCameraMouseInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FlyCameraMouseInput"] = FlyCameraMouseInput; /***/ }), /***/ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts": /*!*********************************************************!*\ !*** ./Cameras/Inputs/followCameraKeyboardMoveInput.ts ***! \*********************************************************/ /*! exports provided: FollowCameraKeyboardMoveInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return FollowCameraKeyboardMoveInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /** * Manage the keyboard inputs to control the movement of a follow camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraKeyboardMoveInput = /** @class */ (function () { function FollowCameraKeyboardMoveInput() { /** * Defines the list of key codes associated with the up action (increase heightOffset) */ this.keysHeightOffsetIncr = [38]; /** * Defines the list of key codes associated with the down action (decrease heightOffset) */ this.keysHeightOffsetDecr = [40]; /** * Defines whether the Alt modifier key is required to move up/down (alter heightOffset) */ this.keysHeightOffsetModifierAlt = false; /** * Defines whether the Ctrl modifier key is required to move up/down (alter heightOffset) */ this.keysHeightOffsetModifierCtrl = false; /** * Defines whether the Shift modifier key is required to move up/down (alter heightOffset) */ this.keysHeightOffsetModifierShift = false; /** * Defines the list of key codes associated with the left action (increase rotationOffset) */ this.keysRotationOffsetIncr = [37]; /** * Defines the list of key codes associated with the right action (decrease rotationOffset) */ this.keysRotationOffsetDecr = [39]; /** * Defines whether the Alt modifier key is required to move left/right (alter rotationOffset) */ this.keysRotationOffsetModifierAlt = false; /** * Defines whether the Ctrl modifier key is required to move left/right (alter rotationOffset) */ this.keysRotationOffsetModifierCtrl = false; /** * Defines whether the Shift modifier key is required to move left/right (alter rotationOffset) */ this.keysRotationOffsetModifierShift = false; /** * Defines the list of key codes associated with the zoom-in action (decrease radius) */ this.keysRadiusIncr = [40]; /** * Defines the list of key codes associated with the zoom-out action (increase radius) */ this.keysRadiusDecr = [38]; /** * Defines whether the Alt modifier key is required to zoom in/out (alter radius value) */ this.keysRadiusModifierAlt = true; /** * Defines whether the Ctrl modifier key is required to zoom in/out (alter radius value) */ this.keysRadiusModifierCtrl = false; /** * Defines whether the Shift modifier key is required to zoom in/out (alter radius value) */ this.keysRadiusModifierShift = false; /** * Defines the rate of change of heightOffset. */ this.heightSensibility = 1; /** * Defines the rate of change of rotationOffset. */ this.rotationSensibility = 1; /** * Defines the rate of change of radius. */ this.radiusSensibility = 1; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FollowCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (!evt.metaKey) { if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { _this._ctrlPressed = evt.ctrlKey; _this._altPressed = evt.altKey; _this._shiftPressed = evt.shiftKey; if (_this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } else { if (_this.keysHeightOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysHeightOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetIncr.indexOf(evt.keyCode) !== -1 || _this.keysRotationOffsetDecr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusIncr.indexOf(evt.keyCode) !== -1 || _this.keysRadiusDecr.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (evt.preventDefault) { if (!noPreventDefault) { evt.preventDefault(); } } } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FollowCameraKeyboardMoveInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FollowCameraKeyboardMoveInput.prototype.checkInputs = function () { var _this = this; if (this._onKeyboardObserver) { this._keys.forEach(function (keyCode) { if (_this.keysHeightOffsetIncr.indexOf(keyCode) !== -1 && _this._modifierHeightOffset()) { _this.camera.heightOffset += _this.heightSensibility; } else if (_this.keysHeightOffsetDecr.indexOf(keyCode) !== -1 && _this._modifierHeightOffset()) { _this.camera.heightOffset -= _this.heightSensibility; } else if (_this.keysRotationOffsetIncr.indexOf(keyCode) !== -1 && _this._modifierRotationOffset()) { _this.camera.rotationOffset += _this.rotationSensibility; _this.camera.rotationOffset %= 360; } else if (_this.keysRotationOffsetDecr.indexOf(keyCode) !== -1 && _this._modifierRotationOffset()) { _this.camera.rotationOffset -= _this.rotationSensibility; _this.camera.rotationOffset %= 360; } else if (_this.keysRadiusIncr.indexOf(keyCode) !== -1 && _this._modifierRadius()) { _this.camera.radius += _this.radiusSensibility; } else if (_this.keysRadiusDecr.indexOf(keyCode) !== -1 && _this._modifierRadius()) { _this.camera.radius -= _this.radiusSensibility; } }); } }; /** * Gets the class name of the current input. * @returns the class name */ FollowCameraKeyboardMoveInput.prototype.getClassName = function () { return "FollowCameraKeyboardMoveInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FollowCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; /** * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to * allow modification of the heightOffset value. */ FollowCameraKeyboardMoveInput.prototype._modifierHeightOffset = function () { return (this.keysHeightOffsetModifierAlt === this._altPressed && this.keysHeightOffsetModifierCtrl === this._ctrlPressed && this.keysHeightOffsetModifierShift === this._shiftPressed); }; /** * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to * allow modification of the rotationOffset value. */ FollowCameraKeyboardMoveInput.prototype._modifierRotationOffset = function () { return (this.keysRotationOffsetModifierAlt === this._altPressed && this.keysRotationOffsetModifierCtrl === this._ctrlPressed && this.keysRotationOffsetModifierShift === this._shiftPressed); }; /** * Check if the pressed modifier keys (Alt/Ctrl/Shift) match those configured to * allow modification of the radius value. */ FollowCameraKeyboardMoveInput.prototype._modifierRadius = function () { return (this.keysRadiusModifierAlt === this._altPressed && this.keysRadiusModifierCtrl === this._ctrlPressed && this.keysRadiusModifierShift === this._shiftPressed); }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetIncr", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetDecr", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierAlt", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierCtrl", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysHeightOffsetModifierShift", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetIncr", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetDecr", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierAlt", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierCtrl", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRotationOffsetModifierShift", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusIncr", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusDecr", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierAlt", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierCtrl", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "keysRadiusModifierShift", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "heightSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "rotationSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FollowCameraKeyboardMoveInput.prototype, "radiusSensibility", void 0); return FollowCameraKeyboardMoveInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]["FollowCameraKeyboardMoveInput"] = FollowCameraKeyboardMoveInput; /***/ }), /***/ "./Cameras/Inputs/followCameraMouseWheelInput.ts": /*!*******************************************************!*\ !*** ./Cameras/Inputs/followCameraMouseWheelInput.ts ***! \*******************************************************/ /*! exports provided: FollowCameraMouseWheelInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return FollowCameraMouseWheelInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Manage the mouse wheel inputs to control a follow camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraMouseWheelInput = /** @class */ (function () { function FollowCameraMouseWheelInput() { /** * Moue wheel controls zoom. (Mouse wheel modifies camera.radius value.) */ this.axisControlRadius = true; /** * Moue wheel controls height. (Mouse wheel modifies camera.heightOffset value.) */ this.axisControlHeight = false; /** * Moue wheel controls angle. (Mouse wheel modifies camera.rotationOffset value.) */ this.axisControlRotation = false; /** * Gets or Set the mouse wheel precision or how fast is the camera moves in * relation to mouseWheel events. */ this.wheelPrecision = 3.0; /** * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0. * It defines the percentage of current camera.radius to use as delta when wheel is used. */ this.wheelDeltaPercentage = 0; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FollowCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; this._wheel = function (p, s) { // sanity check - this should be a PointerWheel event. if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL) { return; } var event = p.event; var delta = 0; // Chrome, Safari: event.deltaY // IE: event.wheelDelta // Firefox: event.detail (inverted) var wheelDelta = Math.max(-1, Math.min(1, (event.deltaY || event.wheelDelta || -event.detail))); if (_this.wheelDeltaPercentage) { console.assert((_this.axisControlRadius + _this.axisControlHeight + _this.axisControlRotation) <= 1, "wheelDeltaPercentage only usable when mouse wheel " + "controlls ONE axis. " + "Currently enabled: " + "axisControlRadius: " + _this.axisControlRadius + ", axisControlHeightOffset: " + _this.axisControlHeight + ", axisControlRotationOffset: " + _this.axisControlRotation); if (_this.axisControlRadius) { delta = wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.radius; } else if (_this.axisControlHeight) { delta = wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.heightOffset; } else if (_this.axisControlRotation) { delta = wheelDelta * 0.01 * _this.wheelDeltaPercentage * _this.camera.rotationOffset; } } else { delta = wheelDelta * _this.wheelPrecision; } if (delta) { if (_this.axisControlRadius) { _this.camera.radius += delta; } else if (_this.axisControlHeight) { _this.camera.heightOffset -= delta; } else if (_this.axisControlRotation) { _this.camera.rotationOffset -= delta; } } if (event.preventDefault) { if (!noPreventDefault) { event.preventDefault(); } } }; this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERWHEEL); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FollowCameraMouseWheelInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; this._wheel = null; } }; /** * Gets the class name of the current intput. * @returns the class name */ FollowCameraMouseWheelInput.prototype.getClassName = function () { return "ArcRotateCameraMouseWheelInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FollowCameraMouseWheelInput.prototype.getSimpleName = function () { return "mousewheel"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "axisControlRadius", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "axisControlHeight", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "axisControlRotation", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "wheelPrecision", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0); return FollowCameraMouseWheelInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FollowCameraMouseWheelInput"] = FollowCameraMouseWheelInput; /***/ }), /***/ "./Cameras/Inputs/followCameraPointersInput.ts": /*!*****************************************************!*\ !*** ./Cameras/Inputs/followCameraPointersInput.ts ***! \*****************************************************/ /*! exports provided: FollowCameraPointersInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return FollowCameraPointersInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/Inputs/BaseCameraPointersInput */ "./Cameras/Inputs/BaseCameraPointersInput.ts"); /** * Manage the pointers inputs to control an follow camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FollowCameraPointersInput = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FollowCameraPointersInput, _super); function FollowCameraPointersInput() { var _this = _super !== null && _super.apply(this, arguments) || this; /** * Defines the pointer angular sensibility along the X axis or how fast is * the camera rotating. * A negative number will reverse the axis direction. */ _this.angularSensibilityX = 1; /** * Defines the pointer angular sensibility along the Y axis or how fast is * the camera rotating. * A negative number will reverse the axis direction. */ _this.angularSensibilityY = 1; /** * Defines the pointer pinch precision or how fast is the camera zooming. * A negative number will reverse the axis direction. */ _this.pinchPrecision = 10000.0; /** * pinchDeltaPercentage will be used instead of pinchPrecision if different * from 0. * It defines the percentage of current camera.radius to use as delta when * pinch zoom is used. */ _this.pinchDeltaPercentage = 0; /** * Pointer X axis controls zoom. (X axis modifies camera.radius value.) */ _this.axisXControlRadius = false; /** * Pointer X axis controls height. (X axis modifies camera.heightOffset value.) */ _this.axisXControlHeight = false; /** * Pointer X axis controls angle. (X axis modifies camera.rotationOffset value.) */ _this.axisXControlRotation = true; /** * Pointer Y axis controls zoom. (Y axis modifies camera.radius value.) */ _this.axisYControlRadius = false; /** * Pointer Y axis controls height. (Y axis modifies camera.heightOffset value.) */ _this.axisYControlHeight = true; /** * Pointer Y axis controls angle. (Y axis modifies camera.rotationOffset value.) */ _this.axisYControlRotation = false; /** * Pinch controls zoom. (Pinch modifies camera.radius value.) */ _this.axisPinchControlRadius = true; /** * Pinch controls height. (Pinch modifies camera.heightOffset value.) */ _this.axisPinchControlHeight = false; /** * Pinch controls angle. (Pinch modifies camera.rotationOffset value.) */ _this.axisPinchControlRotation = false; /** * Log error messages if basic misconfiguration has occurred. */ _this.warningEnable = true; /* Check for obvious misconfiguration. */ _this._warningCounter = 0; return _this; } /** * Gets the class name of the current input. * @returns the class name */ FollowCameraPointersInput.prototype.getClassName = function () { return "FollowCameraPointersInput"; }; FollowCameraPointersInput.prototype.onTouch = function (pointA, offsetX, offsetY) { this._warning(); if (this.axisXControlRotation) { this.camera.rotationOffset += offsetX / this.angularSensibilityX; } else if (this.axisYControlRotation) { this.camera.rotationOffset += offsetY / this.angularSensibilityX; } if (this.axisXControlHeight) { this.camera.heightOffset += offsetX / this.angularSensibilityY; } else if (this.axisYControlHeight) { this.camera.heightOffset += offsetY / this.angularSensibilityY; } if (this.axisXControlRadius) { this.camera.radius -= offsetX / this.angularSensibilityY; } else if (this.axisYControlRadius) { this.camera.radius -= offsetY / this.angularSensibilityY; } }; FollowCameraPointersInput.prototype.onMultiTouch = function (pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition) { if (previousPinchSquaredDistance === 0 && previousMultiTouchPanPosition === null) { // First time this method is called for new pinch. // Next time this is called there will be a // previousPinchSquaredDistance and pinchSquaredDistance to compare. return; } if (pinchSquaredDistance === 0 && multiTouchPanPosition === null) { // Last time this method is called at the end of a pinch. return; } var pinchDelta = (pinchSquaredDistance - previousPinchSquaredDistance) / (this.pinchPrecision * (this.angularSensibilityX + this.angularSensibilityY) / 2); if (this.pinchDeltaPercentage) { pinchDelta *= 0.01 * this.pinchDeltaPercentage; if (this.axisPinchControlRotation) { this.camera.rotationOffset += pinchDelta * this.camera.rotationOffset; } if (this.axisPinchControlHeight) { this.camera.heightOffset += pinchDelta * this.camera.heightOffset; } if (this.axisPinchControlRadius) { this.camera.radius -= pinchDelta * this.camera.radius; } } else { if (this.axisPinchControlRotation) { this.camera.rotationOffset += pinchDelta; } if (this.axisPinchControlHeight) { this.camera.heightOffset += pinchDelta; } if (this.axisPinchControlRadius) { this.camera.radius -= pinchDelta; } } }; FollowCameraPointersInput.prototype._warning = function () { if (!this.warningEnable || this._warningCounter++ % 100 !== 0) { return; } var warn = "It probably only makes sense to control ONE camera " + "property with each pointer axis. Set 'warningEnable = false' " + "if you are sure. Currently enabled: "; console.assert((this.axisXControlRotation + this.axisXControlHeight + this.axisXControlRadius) <= 1, warn + "axisXControlRotation: " + this.axisXControlRotation + ", axisXControlHeight: " + this.axisXControlHeight + ", axisXControlRadius: " + this.axisXControlRadius); console.assert((this.axisYControlRotation + this.axisYControlHeight + this.axisYControlRadius) <= 1, warn + "axisYControlRotation: " + this.axisYControlRotation + ", axisYControlHeight: " + this.axisYControlHeight + ", axisYControlRadius: " + this.axisYControlRadius); console.assert((this.axisPinchControlRotation + this.axisPinchControlHeight + this.axisPinchControlRadius) <= 1, warn + "axisPinchControlRotation: " + this.axisPinchControlRotation + ", axisPinchControlHeight: " + this.axisPinchControlHeight + ", axisPinchControlRadius: " + this.axisPinchControlRadius); }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "angularSensibilityX", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "angularSensibilityY", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "pinchPrecision", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "pinchDeltaPercentage", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisXControlRadius", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisXControlHeight", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisXControlRotation", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisYControlRadius", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisYControlHeight", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisYControlRotation", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisPinchControlRadius", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisPinchControlHeight", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FollowCameraPointersInput.prototype, "axisPinchControlRotation", void 0); return FollowCameraPointersInput; }(_Cameras_Inputs_BaseCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["BaseCameraPointersInput"])); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FollowCameraPointersInput"] = FollowCameraPointersInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts": /*!************************************************************!*\ !*** ./Cameras/Inputs/freeCameraDeviceOrientationInput.ts ***! \************************************************************/ /*! exports provided: FreeCameraDeviceOrientationInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return FreeCameraDeviceOrientationInput; }); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts"); /* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /** * Add orientation input support to the input manager. * @returns the current input manager */ _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addDeviceOrientation = function () { if (!this._deviceOrientationInput) { this._deviceOrientationInput = new FreeCameraDeviceOrientationInput(); this.add(this._deviceOrientationInput); } return this; }; /** * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera. * Screen rotation is taken into account. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraDeviceOrientationInput = /** @class */ (function () { /** * Instantiates a new input * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ function FreeCameraDeviceOrientationInput() { var _this = this; this._screenOrientationAngle = 0; this._screenQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); this._alpha = 0; this._beta = 0; this._gamma = 0; /** * @hidden */ this._onDeviceOrientationChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"](); this._orientationChanged = function () { _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && (window.screen.orientation)['angle'] ? (window.screen.orientation).angle : 0)); _this._screenOrientationAngle = -_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(_this._screenOrientationAngle / 2); _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle)); }; this._deviceOrientation = function (evt) { _this._alpha = evt.alpha !== null ? evt.alpha : 0; _this._beta = evt.beta !== null ? evt.beta : 0; _this._gamma = evt.gamma !== null ? evt.gamma : 0; if (evt.alpha !== null) { _this._onDeviceOrientationChangedObservable.notifyObservers(); } }; this._constantTranform = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5)); this._orientationChanged(); } /** * Can be used to detect if a device orientation sensor is available on a device * @param timeout amount of time in milliseconds to wait for a response from the sensor (default: infinite) * @returns a promise that will resolve on orientation change */ FreeCameraDeviceOrientationInput.WaitForOrientationChangeAsync = function (timeout) { return new Promise(function (res, rej) { var gotValue = false; var eventHandler = function () { window.removeEventListener("deviceorientation", eventHandler); gotValue = true; res(); }; // If timeout is populated reject the promise if (timeout) { setTimeout(function () { if (!gotValue) { window.removeEventListener("deviceorientation", eventHandler); rej("WaitForOrientationChangeAsync timed out"); } }, timeout); } if (typeof (DeviceOrientationEvent) !== "undefined" && typeof DeviceOrientationEvent.requestPermission === 'function') { DeviceOrientationEvent.requestPermission() .then(function (response) { if (response == 'granted') { window.addEventListener("deviceorientation", eventHandler); } else { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Warn("Permission not granted."); } }) .catch(function (error) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Error(error); }); } else { window.addEventListener("deviceorientation", eventHandler); } }); }; Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", { /** * Define the camera controlled by the input. */ get: function () { return this._camera; }, set: function (camera) { var _this = this; this._camera = camera; if (this._camera != null && !this._camera.rotationQuaternion) { this._camera.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"](); } if (this._camera) { this._camera.onDisposeObservable.add(function () { _this._onDeviceOrientationChangedObservable.clear(); }); } }, enumerable: false, configurable: true }); /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var hostWindow = this.camera.getScene().getEngine().getHostWindow(); if (hostWindow) { var eventHandler_1 = function () { hostWindow.addEventListener("orientationchange", _this._orientationChanged); hostWindow.addEventListener("deviceorientation", _this._deviceOrientation); //In certain cases, the attach control is called AFTER orientation was changed, //So this is needed. _this._orientationChanged(); }; if (typeof (DeviceOrientationEvent) !== "undefined" && typeof DeviceOrientationEvent.requestPermission === 'function') { DeviceOrientationEvent.requestPermission() .then(function (response) { if (response === 'granted') { eventHandler_1(); } else { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Warn("Permission not granted."); } }) .catch(function (error) { _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Error(error); }); } else { eventHandler_1(); } } }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) { window.removeEventListener("orientationchange", this._orientationChanged); window.removeEventListener("deviceorientation", this._deviceOrientation); this._alpha = 0; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraDeviceOrientationInput.prototype.checkInputs = function () { //if no device orientation provided, don't update the rotation. //Only testing against alpha under the assumption thatnorientation will never be so exact when set. if (!this._alpha) { return; } _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"].RotationYawPitchRollToRef(_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._alpha), _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._beta), -_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this._gamma), this.camera.rotationQuaternion); this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion); this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform); //Mirror on XY Plane this._camera.rotationQuaternion.z *= -1; this._camera.rotationQuaternion.w *= -1; }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraDeviceOrientationInput.prototype.getClassName = function () { return "FreeCameraDeviceOrientationInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () { return "deviceOrientation"; }; return FreeCameraDeviceOrientationInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraGamepadInput.ts": /*!**************************************************!*\ !*** ./Cameras/Inputs/freeCameraGamepadInput.ts ***! \**************************************************/ /*! exports provided: FreeCameraGamepadInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return FreeCameraGamepadInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /** * Manage the gamepad inputs to control a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraGamepadInput = /** @class */ (function () { function FreeCameraGamepadInput() { /** * Defines the gamepad rotation sensiblity. * This is the threshold from when rotation starts to be accounted for to prevent jittering. */ this.gamepadAngularSensibility = 200; /** * Defines the gamepad move sensiblity. * This is the threshold from when moving starts to be accounted for for to prevent jittering. */ this.gamepadMoveSensibility = 40; this._yAxisScale = 1.0; this._cameraTransform = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Identity(); this._deltaTransform = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); this._vector3 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(); this._vector2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero(); } Object.defineProperty(FreeCameraGamepadInput.prototype, "invertYAxis", { /** * Gets or sets a boolean indicating that Yaxis (for right stick) should be inverted */ get: function () { return this._yAxisScale !== 1.0; }, set: function (value) { this._yAxisScale = value ? -1.0 : 1.0; }, enumerable: false, configurable: true }); /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var manager = this.camera.getScene().gamepadManager; this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) { if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].POSE_ENABLED) { // prioritize XBOX gamepads. if (!_this.gamepad || gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX) { _this.gamepad = gamepad; } } }); this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) { if (_this.gamepad === gamepad) { _this.gamepad = null; } }); this.gamepad = manager.getGamepadByType(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraGamepadInput.prototype.detachControl = function (element) { this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver); this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver); this.gamepad = null; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraGamepadInput.prototype.checkInputs = function () { if (this.gamepad && this.gamepad.leftStick) { var camera = this.camera; var LSValues = this.gamepad.leftStick; var normalizedLX = LSValues.x / this.gamepadMoveSensibility; var normalizedLY = LSValues.y / this.gamepadMoveSensibility; LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0; LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0; var RSValues = this.gamepad.rightStick; if (RSValues) { var normalizedRX = RSValues.x / this.gamepadAngularSensibility; var normalizedRY = (RSValues.y / this.gamepadAngularSensibility) * this._yAxisScale; RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0; RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0; } else { RSValues = { x: 0, y: 0 }; } if (!camera.rotationQuaternion) { _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform); } else { camera.rotationQuaternion.toRotationMatrix(this._cameraTransform); } var speed = camera._computeLocalCameraSpeed() * 50.0; this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform); camera.cameraDirection.addInPlace(this._deltaTransform); this._vector2.copyFromFloats(RSValues.y, RSValues.x); camera.cameraRotation.addInPlace(this._vector2); } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraGamepadInput.prototype.getClassName = function () { return "FreeCameraGamepadInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraGamepadInput.prototype.getSimpleName = function () { return "gamepad"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0); return FreeCameraGamepadInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraGamepadInput"] = FreeCameraGamepadInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts": /*!*******************************************************!*\ !*** ./Cameras/Inputs/freeCameraKeyboardMoveInput.ts ***! \*******************************************************/ /*! exports provided: FreeCameraKeyboardMoveInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return FreeCameraKeyboardMoveInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/keyboardEvents */ "./Events/keyboardEvents.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /** * Manage the keyboard inputs to control the movement of a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraKeyboardMoveInput = /** @class */ (function () { function FreeCameraKeyboardMoveInput() { /** * Gets or Set the list of keyboard keys used to control the forward move of the camera. */ this.keysUp = [38]; /** * Gets or Set the list of keyboard keys used to control the upward move of the camera. */ this.keysUpward = [33]; /** * Gets or Set the list of keyboard keys used to control the backward move of the camera. */ this.keysDown = [40]; /** * Gets or Set the list of keyboard keys used to control the downward move of the camera. */ this.keysDownward = [34]; /** * Gets or Set the list of keyboard keys used to control the left strafe move of the camera. */ this.keysLeft = [37]; /** * Gets or Set the list of keyboard keys used to control the right strafe move of the camera. */ this.keysRight = [39]; this._keys = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; if (this._onCanvasBlurObserver) { return; } this._scene = this.camera.getScene(); this._engine = this._scene.getEngine(); this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () { _this._keys = []; }); this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) { var evt = info.event; if (!evt.metaKey) { if (info.type === _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_3__["KeyboardEventTypes"].KEYDOWN) { if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysUpward.indexOf(evt.keyCode) !== -1 || _this.keysDownward.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index === -1) { _this._keys.push(evt.keyCode); } if (!noPreventDefault) { evt.preventDefault(); } } } else { if (_this.keysUp.indexOf(evt.keyCode) !== -1 || _this.keysDown.indexOf(evt.keyCode) !== -1 || _this.keysLeft.indexOf(evt.keyCode) !== -1 || _this.keysRight.indexOf(evt.keyCode) !== -1 || _this.keysUpward.indexOf(evt.keyCode) !== -1 || _this.keysDownward.indexOf(evt.keyCode) !== -1) { var index = _this._keys.indexOf(evt.keyCode); if (index >= 0) { _this._keys.splice(index, 1); } if (!noPreventDefault) { evt.preventDefault(); } } } } }); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) { if (this._scene) { if (this._onKeyboardObserver) { this._scene.onKeyboardObservable.remove(this._onKeyboardObserver); } if (this._onCanvasBlurObserver) { this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver); } this._onKeyboardObserver = null; this._onCanvasBlurObserver = null; } this._keys = []; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraKeyboardMoveInput.prototype.checkInputs = function () { if (this._onKeyboardObserver) { var camera = this.camera; // Keyboard for (var index = 0; index < this._keys.length; index++) { var keyCode = this._keys[index]; var speed = camera._computeLocalCameraSpeed(); if (this.keysLeft.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(-speed, 0, 0); } else if (this.keysUp.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, speed); } else if (this.keysRight.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(speed, 0, 0); } else if (this.keysDown.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, 0, -speed); } else if (this.keysUpward.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, speed, 0); } else if (this.keysDownward.indexOf(keyCode) !== -1) { camera._localDirection.copyFromFloats(0, -speed, 0); } if (camera.getScene().useRightHandedSystem) { camera._localDirection.z *= -1; } camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection); camera.cameraDirection.addInPlace(camera._transformedDirection); } } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraKeyboardMoveInput.prototype.getClassName = function () { return "FreeCameraKeyboardMoveInput"; }; /** @hidden */ FreeCameraKeyboardMoveInput.prototype._onLostFocus = function () { this._keys = []; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () { return "keyboard"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysUpward", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysDownward", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0); return FreeCameraKeyboardMoveInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraMouseInput.ts": /*!************************************************!*\ !*** ./Cameras/Inputs/freeCameraMouseInput.ts ***! \************************************************/ /*! exports provided: FreeCameraMouseInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return FreeCameraMouseInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /** * Manage the mouse inputs to control the movement of a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraMouseInput = /** @class */ (function () { /** * Manage the mouse inputs to control the movement of a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs * @param touchEnabled Defines if touch is enabled or not */ function FreeCameraMouseInput( /** * Define if touch is enabled in the mouse input */ touchEnabled) { if (touchEnabled === void 0) { touchEnabled = true; } this.touchEnabled = touchEnabled; /** * Defines the buttons associated with the input to handle camera move. */ this.buttons = [0, 1, 2]; /** * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating. */ this.angularSensibility = 2000.0; this.previousPosition = null; /** * Observable for when a pointer move event occurs containing the move offset */ this.onPointerMovedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * @hidden * If the camera should be rotated automatically based on pointer movement */ this._allowCameraRotation = true; } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var engine = this.camera.getEngine(); if (!this._pointerInput) { this._pointerInput = function (p) { var evt = p.event; if (engine.isInVRExclusivePointerMode) { return; } if (!_this.touchEnabled && evt.pointerType === "touch") { return; } if (p.type !== _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) { return; } var srcElement = (evt.srcElement || evt.target); if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN && srcElement) { try { srcElement.setPointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. Execution will continue. } _this.previousPosition = { x: evt.clientX, y: evt.clientY }; if (!noPreventDefault) { evt.preventDefault(); element.focus(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP && srcElement) { try { srcElement.releasePointerCapture(evt.pointerId); } catch (e) { //Nothing to do with the error. } _this.previousPosition = null; if (!noPreventDefault) { evt.preventDefault(); } } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE) { if (!_this.previousPosition || engine.isPointerLock) { return; } var offsetX = evt.clientX - _this.previousPosition.x; var offsetY = evt.clientY - _this.previousPosition.y; if (_this.camera.getScene().useRightHandedSystem) { offsetX *= -1; } if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) { offsetX *= -1; } if (_this._allowCameraRotation) { _this.camera.cameraRotation.y += offsetX / _this.angularSensibility; _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; } _this.onPointerMovedObservable.notifyObservers({ offsetX: offsetX, offsetY: offsetY }); _this.previousPosition = { x: evt.clientX, y: evt.clientY }; if (!noPreventDefault) { evt.preventDefault(); } } }; } this._onMouseMove = function (evt) { if (!engine.isPointerLock) { return; } if (engine.isInVRExclusivePointerMode) { return; } var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0; if (_this.camera.getScene().useRightHandedSystem) { offsetX *= -1; } if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0) { offsetX *= -1; } _this.camera.cameraRotation.y += offsetX / _this.angularSensibility; var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0; _this.camera.cameraRotation.x += offsetY / _this.angularSensibility; _this.previousPosition = null; if (!noPreventDefault) { evt.preventDefault(); } }; this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_4__["PointerEventTypes"].POINTERMOVE); element.addEventListener("mousemove", this._onMouseMove, false); element.addEventListener("contextmenu", this.onContextMenu.bind(this), false); }; /** * Called on JS contextmenu event. * Override this method to provide functionality. */ FreeCameraMouseInput.prototype.onContextMenu = function (evt) { evt.preventDefault(); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraMouseInput.prototype.detachControl = function (element) { if (this._observer && element) { this.camera.getScene().onPointerObservable.remove(this._observer); if (this._onMouseMove) { element.removeEventListener("mousemove", this._onMouseMove); } if (this.onContextMenu) { element.removeEventListener("contextmenu", this.onContextMenu); } if (this.onPointerMovedObservable) { this.onPointerMovedObservable.clear(); } this._observer = null; this._onMouseMove = null; this.previousPosition = null; } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraMouseInput.prototype.getClassName = function () { return "FreeCameraMouseInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraMouseInput.prototype.getSimpleName = function () { return "mouse"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FreeCameraMouseInput.prototype, "buttons", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_2__["serialize"])() ], FreeCameraMouseInput.prototype, "angularSensibility", void 0); return FreeCameraMouseInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["CameraInputTypes"]["FreeCameraMouseInput"] = FreeCameraMouseInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraTouchInput.ts": /*!************************************************!*\ !*** ./Cameras/Inputs/freeCameraTouchInput.ts ***! \************************************************/ /*! exports provided: FreeCameraTouchInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return FreeCameraTouchInput; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /** * Manage the touch inputs to control the movement of a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraTouchInput = /** @class */ (function () { /** * Manage the touch inputs to control the movement of a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs * @param allowMouse Defines if mouse events can be treated as touch events */ function FreeCameraTouchInput( /** * Define if mouse events can be treated as touch events */ allowMouse) { if (allowMouse === void 0) { allowMouse = false; } this.allowMouse = allowMouse; /** * Defines the touch sensibility for rotation. * The higher the faster. */ this.touchAngularSensibility = 200000.0; /** * Defines the touch sensibility for move. * The higher the faster. */ this.touchMoveSensibility = 250.0; this._offsetX = null; this._offsetY = null; this._pointerPressed = new Array(); } /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) { var _this = this; var previousPosition = null; if (this._pointerInput === undefined) { this._onLostFocus = function () { _this._offsetX = null; _this._offsetY = null; }; this._pointerInput = function (p) { var evt = p.event; var isMouseEvent = !_this.camera.getEngine().hostInformation.isMobile && evt instanceof MouseEvent; if (!_this.allowMouse && (evt.pointerType === "mouse" || isMouseEvent)) { return; } if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN) { if (!noPreventDefault) { evt.preventDefault(); } _this._pointerPressed.push(evt.pointerId); if (_this._pointerPressed.length !== 1) { return; } previousPosition = { x: evt.clientX, y: evt.clientY }; } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP) { if (!noPreventDefault) { evt.preventDefault(); } var index = _this._pointerPressed.indexOf(evt.pointerId); if (index === -1) { return; } _this._pointerPressed.splice(index, 1); if (index != 0) { return; } previousPosition = null; _this._offsetX = null; _this._offsetY = null; } else if (p.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE) { if (!noPreventDefault) { evt.preventDefault(); } if (!previousPosition) { return; } var index = _this._pointerPressed.indexOf(evt.pointerId); if (index != 0) { return; } _this._offsetX = evt.clientX - previousPosition.x; _this._offsetY = -(evt.clientY - previousPosition.y); } }; } this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERDOWN | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERUP | _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_3__["PointerEventTypes"].POINTERMOVE); if (this._onLostFocus) { element.addEventListener("blur", this._onLostFocus); } }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraTouchInput.prototype.detachControl = function (element) { if (this._pointerInput && element) { if (this._observer) { this.camera.getScene().onPointerObservable.remove(this._observer); this._observer = null; } if (this._onLostFocus) { element.removeEventListener("blur", this._onLostFocus); this._onLostFocus = null; } this._pointerPressed = []; this._offsetX = null; this._offsetY = null; } }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraTouchInput.prototype.checkInputs = function () { if (this._offsetX && this._offsetY) { var camera = this.camera; camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility; if (this._pointerPressed.length > 1) { camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility; } else { var speed = camera._computeLocalCameraSpeed(); var direction = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, 0, speed * this._offsetY / this.touchMoveSensibility); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix); camera.cameraDirection.addInPlace(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinates(direction, camera._cameraRotationMatrix)); } } }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraTouchInput.prototype.getClassName = function () { return "FreeCameraTouchInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraTouchInput.prototype.getSimpleName = function () { return "touch"; }; Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0); Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([ Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])() ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0); return FreeCameraTouchInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_2__["CameraInputTypes"]["FreeCameraTouchInput"] = FreeCameraTouchInput; /***/ }), /***/ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts": /*!**********************************************************!*\ !*** ./Cameras/Inputs/freeCameraVirtualJoystickInput.ts ***! \**********************************************************/ /*! exports provided: FreeCameraVirtualJoystickInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return FreeCameraVirtualJoystickInput; }); /* harmony import */ var _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/virtualJoystick */ "./Misc/virtualJoystick.ts"); /* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts"); /** * Add virtual joystick input support to the input manager. * @returns the current input manager */ _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addVirtualJoystick = function () { this.add(new FreeCameraVirtualJoystickInput()); return this; }; /** * Manage the Virtual Joystick inputs to control the movement of a free camera. * @see https://doc.babylonjs.com/how_to/customizing_camera_inputs */ var FreeCameraVirtualJoystickInput = /** @class */ (function () { function FreeCameraVirtualJoystickInput() { } /** * Gets the left stick of the virtual joystick. * @returns The virtual Joystick */ FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () { return this._leftjoystick; }; /** * Gets the right stick of the virtual joystick. * @returns The virtual Joystick */ FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () { return this._rightjoystick; }; /** * Update the current camera state depending on the inputs that have been used this frame. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop. */ FreeCameraVirtualJoystickInput.prototype.checkInputs = function () { if (this._leftjoystick) { var camera = this.camera; var speed = camera._computeLocalCameraSpeed() * 50; var cameraTransform = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0); var deltaTransform = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform); camera.cameraDirection = camera.cameraDirection.add(deltaTransform); camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition); if (!this._leftjoystick.pressed) { this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9); } if (!this._rightjoystick.pressed) { this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9); } } }; /** * Attach the input controls to a specific dom element to get the input from. * @param element Defines the element the controls should be listened from * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) */ FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) { this._leftjoystick = new _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"](true); this._leftjoystick.setAxisForUpDown(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].Z); this._leftjoystick.setAxisForLeftRight(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].X); this._leftjoystick.setJoystickSensibility(0.15); this._rightjoystick = new _Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"](false); this._rightjoystick.setAxisForUpDown(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].X); this._rightjoystick.setAxisForLeftRight(_Misc_virtualJoystick__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"].Y); this._rightjoystick.reverseUpDown = true; this._rightjoystick.setJoystickSensibility(0.05); this._rightjoystick.setJoystickColor("yellow"); }; /** * Detach the current controls from the specified dom element. * @param element Defines the element to stop listening the inputs from */ FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) { this._leftjoystick.releaseCanvas(); this._rightjoystick.releaseCanvas(); }; /** * Gets the class name of the current intput. * @returns the class name */ FreeCameraVirtualJoystickInput.prototype.getClassName = function () { return "FreeCameraVirtualJoystickInput"; }; /** * Get the friendly name associated with the input class. * @returns the input friendly name */ FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () { return "virtualJoystick"; }; return FreeCameraVirtualJoystickInput; }()); _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput; /***/ }), /***/ "./Cameras/Inputs/index.ts": /*!*********************************!*\ !*** ./Cameras/Inputs/index.ts ***! \*********************************/ /*! exports provided: ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./arcRotateCameraGamepadInput */ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; }); /* harmony import */ var _arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./arcRotateCameraKeyboardMoveInput */ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraKeyboardMoveInput"]; }); /* harmony import */ var _arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./arcRotateCameraMouseWheelInput */ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCameraMouseWheelInput"]; }); /* harmony import */ var _arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./arcRotateCameraPointersInput */ "./Cameras/Inputs/arcRotateCameraPointersInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_3__["ArcRotateCameraPointersInput"]; }); /* harmony import */ var _arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./arcRotateCameraVRDeviceOrientationInput */ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__["ArcRotateCameraVRDeviceOrientationInput"]; }); /* harmony import */ var _flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flyCameraKeyboardInput */ "./Cameras/Inputs/flyCameraKeyboardInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_5__["FlyCameraKeyboardInput"]; }); /* harmony import */ var _flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./flyCameraMouseInput */ "./Cameras/Inputs/flyCameraMouseInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_6__["FlyCameraMouseInput"]; }); /* harmony import */ var _followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./followCameraKeyboardMoveInput */ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_7__["FollowCameraKeyboardMoveInput"]; }); /* harmony import */ var _followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./followCameraMouseWheelInput */ "./Cameras/Inputs/followCameraMouseWheelInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_8__["FollowCameraMouseWheelInput"]; }); /* harmony import */ var _followCameraPointersInput__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./followCameraPointersInput */ "./Cameras/Inputs/followCameraPointersInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _followCameraPointersInput__WEBPACK_IMPORTED_MODULE_9__["FollowCameraPointersInput"]; }); /* harmony import */ var _freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./freeCameraDeviceOrientationInput */ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_10__["FreeCameraDeviceOrientationInput"]; }); /* harmony import */ var _freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./freeCameraGamepadInput */ "./Cameras/Inputs/freeCameraGamepadInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_11__["FreeCameraGamepadInput"]; }); /* harmony import */ var _freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./freeCameraKeyboardMoveInput */ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_12__["FreeCameraKeyboardMoveInput"]; }); /* harmony import */ var _freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./freeCameraMouseInput */ "./Cameras/Inputs/freeCameraMouseInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_13__["FreeCameraMouseInput"]; }); /* harmony import */ var _freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./freeCameraTouchInput */ "./Cameras/Inputs/freeCameraTouchInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_14__["FreeCameraTouchInput"]; }); /* harmony import */ var _freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./freeCameraVirtualJoystickInput */ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_15__["FreeCameraVirtualJoystickInput"]; }); /***/ }), /***/ "./Cameras/RigModes/index.ts": /*!***********************************!*\ !*** ./Cameras/RigModes/index.ts ***! \***********************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); /* empty/unused harmony star reexport *//* harmony import */ var _stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); /* empty/unused harmony star reexport *//* harmony import */ var _vrRigMode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); /* empty/unused harmony star reexport *//* harmony import */ var _webVRRigMode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRRigMode */ "./Cameras/RigModes/webVRRigMode.ts"); /* empty/unused harmony star reexport */ /***/ }), /***/ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts": /*!*********************************************************!*\ !*** ./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts ***! \*********************************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts"); /* harmony import */ var _PostProcesses_anaglyphPostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/anaglyphPostProcess */ "./PostProcesses/anaglyphPostProcess.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setStereoscopicAnaglyphRigMode = function (camera) { camera._rigCameras[0]._rigPostProcess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_1__["PassPostProcess"](camera.name + "_passthru", 1.0, camera._rigCameras[0]); camera._rigCameras[1]._rigPostProcess = new _PostProcesses_anaglyphPostProcess__WEBPACK_IMPORTED_MODULE_2__["AnaglyphPostProcess"](camera.name + "_anaglyph", 1.0, camera._rigCameras); }; /***/ }), /***/ "./Cameras/RigModes/stereoscopicRigMode.ts": /*!*************************************************!*\ !*** ./Cameras/RigModes/stereoscopicRigMode.ts ***! \*************************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.viewport */ "./Maths/math.viewport.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setStereoscopicRigMode = function (camera) { var isStereoscopicHoriz = camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; var isCrossEye = camera.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED; camera._rigCameras[isCrossEye ? 1 : 0].viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_1__["Viewport"](0, 0, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5); camera._rigCameras[isCrossEye ? 0 : 1].viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_1__["Viewport"](isStereoscopicHoriz ? 0.5 : 0, isStereoscopicHoriz ? 0 : 0.5, isStereoscopicHoriz ? 0.5 : 1.0, isStereoscopicHoriz ? 1.0 : 0.5); }; /***/ }), /***/ "./Cameras/RigModes/vrRigMode.ts": /*!***************************************!*\ !*** ./Cameras/RigModes/vrRigMode.ts ***! \***************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../PostProcesses/vrDistortionCorrectionPostProcess */ "./PostProcesses/vrDistortionCorrectionPostProcess.ts"); /* harmony import */ var _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../PostProcesses/vrMultiviewToSingleviewPostProcess */ "./PostProcesses/vrMultiviewToSingleviewPostProcess.ts"); /* harmony import */ var _VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../VR/vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Maths/math.viewport */ "./Maths/math.viewport.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setVRRigMode = function (camera, rigParams) { var metrics = rigParams.vrCameraMetrics || _VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_4__["VRCameraMetrics"].GetDefault(); camera._rigCameras[0]._cameraRigParams.vrMetrics = metrics; camera._rigCameras[0].viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_6__["Viewport"](0, 0, 0.5, 1.0); camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix; camera._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix; camera._rigCameras[0].getProjectionMatrix = camera._rigCameras[0]._getVRProjectionMatrix; camera._rigCameras[1]._cameraRigParams.vrMetrics = metrics; camera._rigCameras[1].viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_6__["Viewport"](0.5, 0, 0.5, 1.0); camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix; camera._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix; camera._rigCameras[1].getProjectionMatrix = camera._rigCameras[1]._getVRProjectionMatrix; // For multiview on a webVR camera // First multiview will be rendered to camera._multiviewTexture // Then this postprocess will run on each eye to copy the right texture to each eye if (metrics.multiviewEnabled) { if (!camera.getScene().getEngine().getCaps().multiview) { _Misc_logger__WEBPACK_IMPORTED_MODULE_5__["Logger"].Warn("Multiview is not supported, falling back to standard rendering"); metrics.multiviewEnabled = false; } else { camera._useMultiviewToSingleView = true; camera._rigPostProcess = new _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_3__["VRMultiviewToSingleviewPostProcess"]("VRMultiviewToSingleview", camera, metrics.postProcessScaleFactor); } } if (metrics.compensateDistortion) { camera._rigCameras[0]._rigPostProcess = new _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__["VRDistortionCorrectionPostProcess"]("VR_Distort_Compensation_Left", camera._rigCameras[0], false, metrics); camera._rigCameras[1]._rigPostProcess = new _PostProcesses_vrDistortionCorrectionPostProcess__WEBPACK_IMPORTED_MODULE_2__["VRDistortionCorrectionPostProcess"]("VR_Distort_Compensation_Right", camera._rigCameras[1], true, metrics); } }; /***/ }), /***/ "./Cameras/RigModes/webVRRigMode.ts": /*!******************************************!*\ !*** ./Cameras/RigModes/webVRRigMode.ts ***! \******************************************/ /*! no exports provided */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.viewport */ "./Maths/math.viewport.ts"); _camera__WEBPACK_IMPORTED_MODULE_0__["Camera"]._setWebVRRigMode = function (camera, rigParams) { if (rigParams.vrDisplay) { var leftEye = rigParams.vrDisplay.getEyeParameters('left'); var rightEye = rigParams.vrDisplay.getEyeParameters('right'); //Left eye camera._rigCameras[0].viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_2__["Viewport"](0, 0, 0.5, 1.0); camera._rigCameras[0].setCameraRigParameter("left", true); //leaving this for future reference camera._rigCameras[0].setCameraRigParameter("specs", rigParams.specs); camera._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye); camera._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData); camera._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera); camera._rigCameras[0]._cameraRigParams.vrWorkMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[0].getProjectionMatrix = camera._getWebVRProjectionMatrix; camera._rigCameras[0].parent = camera; camera._rigCameras[0]._getViewMatrix = camera._getWebVRViewMatrix; //Right eye camera._rigCameras[1].viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_2__["Viewport"](0.5, 0, 0.5, 1.0); camera._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye); camera._rigCameras[1].setCameraRigParameter("specs", rigParams.specs); camera._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData); camera._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera); camera._rigCameras[1]._cameraRigParams.vrWorkMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](); camera._rigCameras[1].getProjectionMatrix = camera._getWebVRProjectionMatrix; camera._rigCameras[1].parent = camera; camera._rigCameras[1]._getViewMatrix = camera._getWebVRViewMatrix; } }; /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts": /*!*********************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts ***! \*********************************************************/ /*! exports provided: AnaglyphArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return AnaglyphArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) { return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera) * @see https://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphArcRotateCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AnaglyphArcRotateCamera, _super); /** * Creates a new AnaglyphArcRotateCamera * @param name defines camera name * @param alpha defines alpha angle (in radians) * @param beta defines beta angle (in radians) * @param radius defines radius * @param target defines camera target * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) { var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphArcRotateCamera */ AnaglyphArcRotateCamera.prototype.getClassName = function () { return "AnaglyphArcRotateCamera"; }; return AnaglyphArcRotateCamera; }(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphFreeCamera.ts": /*!****************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphFreeCamera.ts ***! \****************************************************/ /*! exports provided: AnaglyphFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return AnaglyphFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) { return function () { return new AnaglyphFreeCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on FreeCamera) * @see https://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphFreeCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AnaglyphFreeCamera, _super); /** * Creates a new AnaglyphFreeCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphFreeCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphFreeCamera */ AnaglyphFreeCamera.prototype.getClassName = function () { return "AnaglyphFreeCamera"; }; return AnaglyphFreeCamera; }(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphGamepadCamera.ts": /*!*******************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphGamepadCamera.ts ***! \*******************************************************/ /*! exports provided: AnaglyphGamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return AnaglyphGamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/gamepadCamera */ "./Cameras/gamepadCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) { return function () { return new AnaglyphGamepadCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on GamepadCamera) * @see https://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphGamepadCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AnaglyphGamepadCamera, _super); /** * Creates a new AnaglyphGamepadCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphGamepadCamera */ AnaglyphGamepadCamera.prototype.getClassName = function () { return "AnaglyphGamepadCamera"; }; return AnaglyphGamepadCamera; }(_Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__["GamepadCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/anaglyphUniversalCamera.ts": /*!*********************************************************!*\ !*** ./Cameras/Stereoscopic/anaglyphUniversalCamera.ts ***! \*********************************************************/ /*! exports provided: AnaglyphUniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return AnaglyphUniversalCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/universalCamera */ "./Cameras/universalCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicAnaglyphRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicAnaglyphRigMode */ "./Cameras/RigModes/stereoscopicAnaglyphRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) { return function () { return new AnaglyphUniversalCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, scene); }; }); /** * Camera used to simulate anaglyphic rendering (based on UniversalCamera) * @see https://doc.babylonjs.com/features/cameras#anaglyph-cameras */ var AnaglyphUniversalCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AnaglyphUniversalCamera, _super); /** * Creates a new AnaglyphUniversalCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param scene defines the hosting scene */ function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns AnaglyphUniversalCamera */ AnaglyphUniversalCamera.prototype.getClassName = function () { return "AnaglyphUniversalCamera"; }; return AnaglyphUniversalCamera; }(_Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__["UniversalCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/index.ts": /*!***************************************!*\ !*** ./Cameras/Stereoscopic/index.ts ***! \***************************************/ /*! exports provided: AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _anaglyphArcRotateCamera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./anaglyphArcRotateCamera */ "./Cameras/Stereoscopic/anaglyphArcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _anaglyphArcRotateCamera__WEBPACK_IMPORTED_MODULE_0__["AnaglyphArcRotateCamera"]; }); /* harmony import */ var _anaglyphFreeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./anaglyphFreeCamera */ "./Cameras/Stereoscopic/anaglyphFreeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _anaglyphFreeCamera__WEBPACK_IMPORTED_MODULE_1__["AnaglyphFreeCamera"]; }); /* harmony import */ var _anaglyphGamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./anaglyphGamepadCamera */ "./Cameras/Stereoscopic/anaglyphGamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _anaglyphGamepadCamera__WEBPACK_IMPORTED_MODULE_2__["AnaglyphGamepadCamera"]; }); /* harmony import */ var _anaglyphUniversalCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./anaglyphUniversalCamera */ "./Cameras/Stereoscopic/anaglyphUniversalCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _anaglyphUniversalCamera__WEBPACK_IMPORTED_MODULE_3__["AnaglyphUniversalCamera"]; }); /* harmony import */ var _stereoscopicArcRotateCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./stereoscopicArcRotateCamera */ "./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _stereoscopicArcRotateCamera__WEBPACK_IMPORTED_MODULE_4__["StereoscopicArcRotateCamera"]; }); /* harmony import */ var _stereoscopicFreeCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./stereoscopicFreeCamera */ "./Cameras/Stereoscopic/stereoscopicFreeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _stereoscopicFreeCamera__WEBPACK_IMPORTED_MODULE_5__["StereoscopicFreeCamera"]; }); /* harmony import */ var _stereoscopicGamepadCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./stereoscopicGamepadCamera */ "./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _stereoscopicGamepadCamera__WEBPACK_IMPORTED_MODULE_6__["StereoscopicGamepadCamera"]; }); /* harmony import */ var _stereoscopicUniversalCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./stereoscopicUniversalCamera */ "./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _stereoscopicUniversalCamera__WEBPACK_IMPORTED_MODULE_7__["StereoscopicUniversalCamera"]; }); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts": /*!*************************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicArcRotateCamera.ts ***! \*************************************************************/ /*! exports provided: StereoscopicArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return StereoscopicArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) { return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera) * @see https://doc.babylonjs.com/features/cameras */ var StereoscopicArcRotateCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StereoscopicArcRotateCamera, _super); /** * Creates a new StereoscopicArcRotateCamera * @param name defines camera name * @param alpha defines alpha angle (in radians) * @param beta defines beta angle (in radians) * @param radius defines radius * @param target defines camera target * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicArcRotateCamera */ StereoscopicArcRotateCamera.prototype.getClassName = function () { return "StereoscopicArcRotateCamera"; }; return StereoscopicArcRotateCamera; }(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicFreeCamera.ts": /*!********************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicFreeCamera.ts ***! \********************************************************/ /*! exports provided: StereoscopicFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return StereoscopicFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) { return function () { return new StereoscopicFreeCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on FreeCamera) * @see https://doc.babylonjs.com/features/cameras */ var StereoscopicFreeCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StereoscopicFreeCamera, _super); /** * Creates a new StereoscopicFreeCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicFreeCamera */ StereoscopicFreeCamera.prototype.getClassName = function () { return "StereoscopicFreeCamera"; }; return StereoscopicFreeCamera; }(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts": /*!***********************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicGamepadCamera.ts ***! \***********************************************************/ /*! exports provided: StereoscopicGamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return StereoscopicGamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/gamepadCamera */ "./Cameras/gamepadCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) { return function () { return new StereoscopicGamepadCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on GamepadCamera) * @see https://doc.babylonjs.com/features/cameras */ var StereoscopicGamepadCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StereoscopicGamepadCamera, _super); /** * Creates a new StereoscopicGamepadCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicGamepadCamera */ StereoscopicGamepadCamera.prototype.getClassName = function () { return "StereoscopicGamepadCamera"; }; return StereoscopicGamepadCamera; }(_Cameras_gamepadCamera__WEBPACK_IMPORTED_MODULE_2__["GamepadCamera"])); /***/ }), /***/ "./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts": /*!*************************************************************!*\ !*** ./Cameras/Stereoscopic/stereoscopicUniversalCamera.ts ***! \*************************************************************/ /*! exports provided: StereoscopicUniversalCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return StereoscopicUniversalCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/universalCamera */ "./Cameras/universalCamera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_stereoscopicRigMode__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../RigModes/stereoscopicRigMode */ "./Cameras/RigModes/stereoscopicRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) { return function () { return new StereoscopicUniversalCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); }; }); /** * Camera used to simulate stereoscopic rendering (based on UniversalCamera) * @see https://doc.babylonjs.com/features/cameras */ var StereoscopicUniversalCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StereoscopicUniversalCamera, _super); /** * Creates a new StereoscopicUniversalCamera * @param name defines camera name * @param position defines initial position * @param interaxialDistance defines distance between each color axis * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under * @param scene defines the hosting scene */ function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) { var _this = _super.call(this, name, position, scene) || this; _this.interaxialDistance = interaxialDistance; _this.isStereoscopicSideBySide = isStereoscopicSideBySide; _this.setCameraRigMode(isStereoscopicSideBySide ? _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance }); return _this; } /** * Gets camera class name * @returns StereoscopicUniversalCamera */ StereoscopicUniversalCamera.prototype.getClassName = function () { return "StereoscopicUniversalCamera"; }; return StereoscopicUniversalCamera; }(_Cameras_universalCamera__WEBPACK_IMPORTED_MODULE_2__["UniversalCamera"])); /***/ }), /***/ "./Cameras/VR/index.ts": /*!*****************************!*\ !*** ./Cameras/VR/index.ts ***! \*****************************/ /*! exports provided: VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_0__["VRCameraMetrics"]; }); /* harmony import */ var _vrDeviceOrientationArcRotateCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vrDeviceOrientationArcRotateCamera */ "./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _vrDeviceOrientationArcRotateCamera__WEBPACK_IMPORTED_MODULE_1__["VRDeviceOrientationArcRotateCamera"]; }); /* harmony import */ var _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_2__["VRDeviceOrientationFreeCamera"]; }); /* harmony import */ var _vrDeviceOrientationGamepadCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrDeviceOrientationGamepadCamera */ "./Cameras/VR/vrDeviceOrientationGamepadCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _vrDeviceOrientationGamepadCamera__WEBPACK_IMPORTED_MODULE_3__["VRDeviceOrientationGamepadCamera"]; }); /* harmony import */ var _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./vrExperienceHelper */ "./Cameras/VR/vrExperienceHelper.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__["OnAfterEnteringVRObservableEvent"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _vrExperienceHelper__WEBPACK_IMPORTED_MODULE_4__["VRExperienceHelper"]; }); /* harmony import */ var _webVRCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./webVRCamera */ "./Cameras/VR/webVRCamera.ts"); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _webVRCamera__WEBPACK_IMPORTED_MODULE_5__["WebVRFreeCamera"]; }); /***/ }), /***/ "./Cameras/VR/vrCameraMetrics.ts": /*!***************************************!*\ !*** ./Cameras/VR/vrCameraMetrics.ts ***! \***************************************/ /*! exports provided: VRCameraMetrics */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return VRCameraMetrics; }); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /** * This represents all the required metrics to create a VR camera. * @see https://doc.babylonjs.com/babylon101/cameras#device-orientation-camera */ var VRCameraMetrics = /** @class */ (function () { function VRCameraMetrics() { /** * Define if the current vr camera should compensate the distortion of the lense or not. */ this.compensateDistortion = true; /** * Defines if multiview should be enabled when rendering (Default: false) */ this.multiviewEnabled = false; } Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", { /** * Gets the rendering aspect ratio based on the provided resolutions. */ get: function () { return this.hResolution / (2 * this.vResolution); }, enumerable: false, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", { /** * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes. */ get: function () { return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance))); }, enumerable: false, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", { /** * @hidden */ get: function () { var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); var h = (4 * meters) / this.hScreenSize; return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(h, 0, 0); }, enumerable: false, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", { /** * @hidden */ get: function () { var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2); var h = (4 * meters) / this.hScreenSize; return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-h, 0, 0); }, enumerable: false, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", { /** * @hidden */ get: function () { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(0.5 * this.interpupillaryDistance, 0, 0); }, enumerable: false, configurable: true }); Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", { /** * @hidden */ get: function () { return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-0.5 * this.interpupillaryDistance, 0, 0); }, enumerable: false, configurable: true }); /** * Get the default VRMetrics based on the most generic setup. * @returns the default vr metrics */ VRCameraMetrics.GetDefault = function () { var result = new VRCameraMetrics(); result.hResolution = 1280; result.vResolution = 800; result.hScreenSize = 0.149759993; result.vScreenSize = 0.0935999975; result.vScreenCenter = 0.0467999987; result.eyeToScreenDistance = 0.0410000011; result.lensSeparationDistance = 0.0635000020; result.interpupillaryDistance = 0.0640000030; result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0]; result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0]; result.postProcessScaleFactor = 1.714605507808412; result.lensCenterOffset = 0.151976421; return result; }; return VRCameraMetrics; }()); /***/ }), /***/ "./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts": /*!**********************************************************!*\ !*** ./Cameras/VR/vrDeviceOrientationArcRotateCamera.ts ***! \**********************************************************/ /*! exports provided: VRDeviceOrientationArcRotateCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return VRDeviceOrientationArcRotateCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts"); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _Inputs_arcRotateCameraVRDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Inputs/arcRotateCameraVRDeviceOrientationInput */ "./Cameras/Inputs/arcRotateCameraVRDeviceOrientationInput.ts"); /* harmony import */ var _RigModes_vrRigMode__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../RigModes/vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) { return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); /** * Camera used to simulate VR rendering (based on ArcRotateCamera) * @see https://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras */ var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VRDeviceOrientationArcRotateCamera, _super); /** * Creates a new VRDeviceOrientationArcRotateCamera * @param name defines camera name * @param alpha defines the camera rotation along the logitudinal axis * @param beta defines the camera rotation along the latitudinal axis * @param radius defines the camera distance from its target * @param target defines the camera target * @param scene defines the scene the camera belongs to * @param compensateDistortion defines if the camera needs to compensate the lens distorsion * @param vrCameraMetrics defines the vr metrics associated to the camera */ function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__["VRCameraMetrics"].GetDefault(); } var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this; vrCameraMetrics.compensateDistortion = compensateDistortion; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); _this.inputs.addVRDeviceOrientation(); return _this; } /** * Gets camera class name * @returns VRDeviceOrientationArcRotateCamera */ VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () { return "VRDeviceOrientationArcRotateCamera"; }; return VRDeviceOrientationArcRotateCamera; }(_Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"])); /***/ }), /***/ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts": /*!*****************************************************!*\ !*** ./Cameras/VR/vrDeviceOrientationFreeCamera.ts ***! \*****************************************************/ /*! exports provided: VRDeviceOrientationFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return VRDeviceOrientationFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _RigModes_vrRigMode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../RigModes/vrRigMode */ "./Cameras/RigModes/vrRigMode.ts"); // Side effect import to define the stereoscopic mode. _node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) { return function () { return new VRDeviceOrientationFreeCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); /** * Camera used to simulate VR rendering (based on FreeCamera) * @see https://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras */ var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VRDeviceOrientationFreeCamera, _super); /** * Creates a new VRDeviceOrientationFreeCamera * @param name defines camera name * @param position defines the start position of the camera * @param scene defines the scene the camera belongs to * @param compensateDistortion defines if the camera needs to compensate the lens distorsion * @param vrCameraMetrics defines the vr metrics associated to the camera */ function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_3__["VRCameraMetrics"].GetDefault(); } var _this = _super.call(this, name, position, scene) || this; vrCameraMetrics.compensateDistortion = compensateDistortion; _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics }); return _this; } /** * Gets camera class name * @returns VRDeviceOrientationFreeCamera */ VRDeviceOrientationFreeCamera.prototype.getClassName = function () { return "VRDeviceOrientationFreeCamera"; }; return VRDeviceOrientationFreeCamera; }(_Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_2__["DeviceOrientationCamera"])); /***/ }), /***/ "./Cameras/VR/vrDeviceOrientationGamepadCamera.ts": /*!********************************************************!*\ !*** ./Cameras/VR/vrDeviceOrientationGamepadCamera.ts ***! \********************************************************/ /*! exports provided: VRDeviceOrientationGamepadCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return VRDeviceOrientationGamepadCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); /* harmony import */ var _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); _node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) { return function () { return new VRDeviceOrientationGamepadCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); }; }); /** * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera) * @see https://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras */ var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VRDeviceOrientationGamepadCamera, _super); /** * Creates a new VRDeviceOrientationGamepadCamera * @param name defines camera name * @param position defines the start position of the camera * @param scene defines the scene the camera belongs to * @param compensateDistortion defines if the camera needs to compensate the lens distorsion * @param vrCameraMetrics defines the vr metrics associated to the camera */ function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) { if (compensateDistortion === void 0) { compensateDistortion = true; } if (vrCameraMetrics === void 0) { vrCameraMetrics = _vrCameraMetrics__WEBPACK_IMPORTED_MODULE_2__["VRCameraMetrics"].GetDefault(); } var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this; _this.inputs.addGamepad(); return _this; } /** * Gets camera class name * @returns VRDeviceOrientationGamepadCamera */ VRDeviceOrientationGamepadCamera.prototype.getClassName = function () { return "VRDeviceOrientationGamepadCamera"; }; return VRDeviceOrientationGamepadCamera; }(_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_1__["VRDeviceOrientationFreeCamera"])); /***/ }), /***/ "./Cameras/VR/vrExperienceHelper.ts": /*!******************************************!*\ !*** ./Cameras/VR/vrExperienceHelper.ts ***! \******************************************/ /*! exports provided: OnAfterEnteringVRObservableEvent, VRExperienceHelper */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return OnAfterEnteringVRObservableEvent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return VRExperienceHelper; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Cameras/targetCamera */ "./Cameras/targetCamera.ts"); /* harmony import */ var _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Cameras/deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts"); /* harmony import */ var _Cameras_VR_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Cameras/VR/vrDeviceOrientationFreeCamera */ "./Cameras/VR/vrDeviceOrientationFreeCamera.ts"); /* harmony import */ var _Cameras_VR_webVRCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Cameras/VR/webVRCamera */ "./Cameras/VR/webVRCamera.ts"); /* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Events/pointerEvents */ "./Events/pointerEvents.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /* harmony import */ var _Gamepads_Controllers_webVRController__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Gamepads/Controllers/webVRController */ "./Gamepads/Controllers/webVRController.ts"); /* harmony import */ var _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Gamepads/xboxGamepad */ "./Gamepads/xboxGamepad.ts"); /* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts"); /* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts"); /* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts"); /* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Materials/standardMaterial */ "./Materials/standardMaterial.ts"); /* harmony import */ var _Materials_Textures_dynamicTexture__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../Materials/Textures/dynamicTexture */ "./Materials/Textures/dynamicTexture.ts"); /* harmony import */ var _PostProcesses_imageProcessingPostProcess__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../PostProcesses/imageProcessingPostProcess */ "./PostProcesses/imageProcessingPostProcess.ts"); /* harmony import */ var _Animations_easing__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Animations/easing */ "./Animations/easing.ts"); /* harmony import */ var _Animations_animation__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Animations/animation */ "./Animations/animation.ts"); /* harmony import */ var _Cameras_VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Cameras/VR/vrCameraMetrics */ "./Cameras/VR/vrCameraMetrics.ts"); /* harmony import */ var _Meshes_Builders_groundBuilder__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Meshes/Builders/groundBuilder */ "./Meshes/Builders/groundBuilder.ts"); /* harmony import */ var _Meshes_Builders_torusBuilder__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../Meshes/Builders/torusBuilder */ "./Meshes/Builders/torusBuilder.ts"); /* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts"); /* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts"); /* harmony import */ var _Animations_animatable__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ../../Animations/animatable */ "./Animations/animatable.ts"); /* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ../../Maths/math.axis */ "./Maths/math.axis.ts"); /* harmony import */ var _XR_webXRSessionManager__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ../../XR/webXRSessionManager */ "./XR/webXRSessionManager.ts"); /* harmony import */ var _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ../../XR/webXRTypes */ "./XR/webXRTypes.ts"); var VRExperienceHelperGazer = /** @class */ (function () { function VRExperienceHelperGazer(scene, gazeTrackerToClone) { if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; } this.scene = scene; /** @hidden */ this._pointerDownOnMeshAsked = false; /** @hidden */ this._isActionableMesh = false; /** @hidden */ this._teleportationRequestInitiated = false; /** @hidden */ this._teleportationBackRequestInitiated = false; /** @hidden */ this._rotationRightAsked = false; /** @hidden */ this._rotationLeftAsked = false; /** @hidden */ this._dpadPressed = true; /** @hidden */ this._activePointer = false; this._id = VRExperienceHelperGazer._idCounter++; // Gaze tracker if (!gazeTrackerToClone) { this._gazeTracker = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__["Mesh"].CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false); this._gazeTracker.bakeCurrentTransformIntoVertices(); this._gazeTracker.isPickable = false; this._gazeTracker.isVisible = false; var targetMat = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_18__["StandardMaterial"]("targetMat", scene); targetMat.specularColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"].Black(); targetMat.emissiveColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.7, 0.7, 0.7); targetMat.backFaceCulling = false; this._gazeTracker.material = targetMat; } else { this._gazeTracker = gazeTrackerToClone.clone("gazeTracker"); } } /** @hidden */ VRExperienceHelperGazer.prototype._getForwardRay = function (length) { return new _Culling_ray__WEBPACK_IMPORTED_MODULE_16__["Ray"](_Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, 0, length)); }; /** @hidden */ VRExperienceHelperGazer.prototype._selectionPointerDown = function () { this._pointerDownOnMeshAsked = true; if (this._currentHit) { this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id }); } }; /** @hidden */ VRExperienceHelperGazer.prototype._selectionPointerUp = function () { if (this._currentHit) { this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id }); } this._pointerDownOnMeshAsked = false; }; /** @hidden */ VRExperienceHelperGazer.prototype._activatePointer = function () { this._activePointer = true; }; /** @hidden */ VRExperienceHelperGazer.prototype._deactivatePointer = function () { this._activePointer = false; }; /** @hidden */ VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) { if (distance === void 0) { distance = 100; } }; VRExperienceHelperGazer.prototype.dispose = function () { this._interactionsEnabled = false; this._teleportationEnabled = false; if (this._gazeTracker) { this._gazeTracker.dispose(); } }; VRExperienceHelperGazer._idCounter = 0; return VRExperienceHelperGazer; }()); var VRExperienceHelperControllerGazer = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VRExperienceHelperControllerGazer, _super); function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) { var _this = _super.call(this, scene, gazeTrackerToClone) || this; _this.webVRController = webVRController; // Laser pointer _this._laserPointer = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__["Mesh"].CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false); var laserPointerMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_18__["StandardMaterial"]("laserPointerMat", scene); laserPointerMaterial.emissiveColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.7, 0.7, 0.7); laserPointerMaterial.alpha = 0.6; _this._laserPointer.material = laserPointerMaterial; _this._laserPointer.rotation.x = Math.PI / 2; _this._laserPointer.position.z = -0.5; _this._laserPointer.isVisible = false; _this._laserPointer.isPickable = false; if (!webVRController.mesh) { // Create an empty mesh that is used prior to loading the high quality model var preloadMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__["Mesh"]("preloadControllerMesh", scene); var preloadPointerPose = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__["Mesh"](_Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_12__["PoseEnabledController"].POINTING_POSE, scene); preloadPointerPose.rotation.x = -0.7; preloadMesh.addChild(preloadPointerPose); webVRController.attachToMesh(preloadMesh); } _this._setLaserPointerParent(webVRController.mesh); _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) { _this._setLaserPointerParent(mesh); }); return _this; } VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) { return this.webVRController.getForwardRay(length); }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._activatePointer = function () { _super.prototype._activatePointer.call(this); this._laserPointer.isVisible = true; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () { _super.prototype._deactivatePointer.call(this); this._laserPointer.isVisible = false; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) { this._laserPointer.material.emissiveColor = color; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._setLaserPointerLightingDisabled = function (disabled) { this._laserPointer.material.disableLighting = disabled; }; /** @hidden */ VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) { var makeNotPick = function (root) { root.isPickable = false; root.getChildMeshes().forEach(function (c) { makeNotPick(c); }); }; makeNotPick(mesh); var meshChildren = mesh.getChildren(undefined, false); var laserParent = mesh; this.webVRController._pointingPoseNode = null; for (var i = 0; i < meshChildren.length; i++) { if (meshChildren[i].name && meshChildren[i].name.indexOf(_Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_12__["PoseEnabledController"].POINTING_POSE) >= 0) { laserParent = meshChildren[i]; this.webVRController._pointingPoseNode = laserParent; break; } } this._laserPointer.parent = laserParent; }; VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) { if (distance === void 0) { distance = 100; } this._laserPointer.scaling.y = distance; this._laserPointer.position.z = -distance / 2; }; VRExperienceHelperControllerGazer.prototype.dispose = function () { _super.prototype.dispose.call(this); this._laserPointer.dispose(); if (this._meshAttachedObserver) { this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver); } }; return VRExperienceHelperControllerGazer; }(VRExperienceHelperGazer)); var VRExperienceHelperCameraGazer = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VRExperienceHelperCameraGazer, _super); function VRExperienceHelperCameraGazer(getCamera, scene) { var _this = _super.call(this, scene) || this; _this.getCamera = getCamera; return _this; } VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) { var camera = this.getCamera(); if (camera) { return camera.getForwardRay(length); } else { return new _Culling_ray__WEBPACK_IMPORTED_MODULE_16__["Ray"](_Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Forward()); } }; return VRExperienceHelperCameraGazer; }(VRExperienceHelperGazer)); /** * Event containing information after VR has been entered */ var OnAfterEnteringVRObservableEvent = /** @class */ (function () { function OnAfterEnteringVRObservableEvent() { } return OnAfterEnteringVRObservableEvent; }()); /** * Helps to quickly add VR support to an existing scene. * See https://doc.babylonjs.com/how_to/webvr_helper */ var VRExperienceHelper = /** @class */ (function () { /** * Instantiates a VRExperienceHelper. * Helps to quickly add VR support to an existing scene. * @param scene The scene the VRExperienceHelper belongs to. * @param webVROptions Options to modify the vr experience helper's behavior. */ function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) { var _this = this; if (webVROptions === void 0) { webVROptions = {}; } this.webVROptions = webVROptions; // Can the system support WebVR, even if a headset isn't plugged in? this._webVRsupported = false; // If WebVR is supported, is a headset plugged in and are we ready to present? this._webVRready = false; // Are we waiting for the requestPresent callback to complete? this._webVRrequesting = false; // Are we presenting to the headset right now? (this is the vrDevice state) this._webVRpresenting = false; // Are we presenting in the fullscreen fallback? this._fullscreenVRpresenting = false; /** * Gets or sets a boolean indicating that gaze can be enabled even if pointer lock is not engage (useful on iOS where fullscreen mode and pointer lock are not supported) */ this.enableGazeEvenWhenNoPointerLock = false; /** * Gets or sets a boolean indicating that the VREXperienceHelper will exit VR if double tap is detected */ this.exitVROnDoubleTap = true; /** * Observable raised right before entering VR. */ this.onEnteringVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when entering VR has completed. */ this.onAfterEnteringVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when exiting VR. */ this.onExitingVRObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when controller mesh is loaded. */ this.onControllerMeshLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); this._useCustomVRButton = false; this._teleportationRequested = false; this._teleportActive = false; this._floorMeshesCollection = []; this._teleportationMode = VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME; this._teleportationTime = 122; this._teleportationSpeed = 20; this._rotationAllowed = true; this._teleportBackwardsVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, -1, -1); this._isDefaultTeleportationTarget = true; this._teleportationFillColor = "#444444"; this._teleportationBorderColor = "#FFFFFF"; this._rotationAngle = 0; this._haloCenter = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, 0, 0); this._padSensibilityUp = 0.65; this._padSensibilityDown = 0.35; this._leftController = null; this._rightController = null; this._gazeColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.7, 0.7, 0.7); this._laserColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.7, 0.7, 0.7); this._pickedLaserColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.2, 0.2, 1); this._pickedGazeColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0, 0, 1); /** * Observable raised when a new mesh is selected based on meshSelectionPredicate */ this.onNewMeshSelected = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when a new mesh is selected based on meshSelectionPredicate. * This observable will provide the mesh and the controller used to select the mesh */ this.onMeshSelectedWithController = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when a new mesh is picked based on meshSelectionPredicate */ this.onNewMeshPicked = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised before camera teleportation */ this.onBeforeCameraTeleport = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised after camera teleportation */ this.onAfterCameraTeleport = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Observable raised when current selected mesh gets unselected */ this.onSelectedMeshUnselected = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"](); /** * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept. */ this.teleportationEnabled = true; this._teleportationInitialized = false; this._interactionsEnabled = false; this._interactionsRequested = false; this._displayGaze = true; this._displayLaserPointer = true; /** * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes */ this.updateGazeTrackerScale = true; /** * If the gaze trackers color should be updated when selecting meshes */ this.updateGazeTrackerColor = true; /** * If the controller laser color should be updated when selecting meshes */ this.updateControllerLaserColor = true; /** * Defines whether or not Pointer lock should be requested when switching to * full screen. */ this.requestPointerLockOnFullScreen = true; /** * Was the XR test done already. If this is true AND this.xr exists, xr is initialized. * If this is true and no this.xr, xr exists but is not supported, using WebVR. */ this.xrTestDone = false; this._onResize = function () { _this.moveButtonToBottomRight(); if (_this._fullscreenVRpresenting && _this._webVRready) { _this.exitVR(); } }; this._onFullscreenChange = function () { var anyDoc = document; if (anyDoc.fullscreen !== undefined) { _this._fullscreenVRpresenting = document.fullscreen; } else if (anyDoc.mozFullScreen !== undefined) { _this._fullscreenVRpresenting = anyDoc.mozFullScreen; } else if (anyDoc.webkitIsFullScreen !== undefined) { _this._fullscreenVRpresenting = anyDoc.webkitIsFullScreen; } else if (anyDoc.msIsFullScreen !== undefined) { _this._fullscreenVRpresenting = anyDoc.msIsFullScreen; } else if (document.msFullscreenElement !== undefined) { _this._fullscreenVRpresenting = document.msFullscreenElement; } if (!_this._fullscreenVRpresenting && _this._inputElement) { _this.exitVR(); if (!_this._useCustomVRButton && _this._btnVR) { _this._btnVR.style.top = _this._inputElement.offsetTop + _this._inputElement.offsetHeight - 70 + "px"; _this._btnVR.style.left = _this._inputElement.offsetLeft + _this._inputElement.offsetWidth - 100 + "px"; // make sure the button is visible after setting its position _this.updateButtonVisibility(); } } }; this._cachedAngularSensibility = { angularSensibilityX: null, angularSensibilityY: null, angularSensibility: null }; this.beforeRender = function () { if (_this._leftController && _this._leftController._activePointer) { _this._castRayAndSelectObject(_this._leftController); } if (_this._rightController && _this._rightController._activePointer) { _this._castRayAndSelectObject(_this._rightController); } if (_this._noControllerIsActive && (_this._scene.getEngine().isPointerLock || _this.enableGazeEvenWhenNoPointerLock)) { _this._castRayAndSelectObject(_this._cameraGazer); } else { _this._cameraGazer._gazeTracker.isVisible = false; } }; this._onNewGamepadConnected = function (gamepad) { if (gamepad.type !== _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_11__["Gamepad"].POSE_ENABLED) { if (gamepad.leftStick) { gamepad.onleftstickchanged(function (stickValues) { if (_this._teleportationInitialized && _this.teleportationEnabled) { // Listening to classic/xbox gamepad only if no VR controller is active if ((!_this._leftController && !_this._rightController) || ((_this._leftController && !_this._leftController._activePointer) && (_this._rightController && !_this._rightController._activePointer))) { _this._checkTeleportWithRay(stickValues, _this._cameraGazer); _this._checkTeleportBackwards(stickValues, _this._cameraGazer); } } }); } if (gamepad.rightStick) { gamepad.onrightstickchanged(function (stickValues) { if (_this._teleportationInitialized) { _this._checkRotate(stickValues, _this._cameraGazer); } }); } if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_11__["Gamepad"].XBOX) { gamepad.onbuttondown(function (buttonPressed) { if (_this._interactionsEnabled && buttonPressed === _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_14__["Xbox360Button"].A) { _this._cameraGazer._selectionPointerDown(); } }); gamepad.onbuttonup(function (buttonPressed) { if (_this._interactionsEnabled && buttonPressed === _Gamepads_xboxGamepad__WEBPACK_IMPORTED_MODULE_14__["Xbox360Button"].A) { _this._cameraGazer._selectionPointerUp(); } }); } } else { var webVRController = gamepad; var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker); if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) { _this._rightController = controller; } else { _this._leftController = controller; } _this._tryEnableInteractionOnController(controller); } }; // This only succeeds if the controller's mesh exists for the controller so this must be called whenever new controller is connected or when mesh is loaded this._tryEnableInteractionOnController = function (controller) { if (_this._interactionsRequested && !controller._interactionsEnabled) { _this._enableInteractionOnController(controller); } if (_this._teleportationRequested && !controller._teleportationEnabled) { _this._enableTeleportationOnController(controller); } }; this._onNewGamepadDisconnected = function (gamepad) { if (gamepad instanceof _Gamepads_Controllers_webVRController__WEBPACK_IMPORTED_MODULE_13__["WebVRController"]) { if (gamepad.hand === "left" && _this._leftController != null) { _this._leftController.dispose(); _this._leftController = null; } if (gamepad.hand === "right" && _this._rightController != null) { _this._rightController.dispose(); _this._rightController = null; } } }; this._workingVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Zero(); this._workingQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].Identity(); this._workingMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Matrix"].Identity(); this._scene = scene; this._inputElement = scene.getEngine().getInputElement(); // check for VR support: var vrSupported = 'getVRDisplays' in navigator; // no VR support? force XR if (!vrSupported) { webVROptions.useXR = true; } // Parse options if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) { webVROptions.createFallbackVRDeviceOrientationFreeCamera = true; } if (webVROptions.createDeviceOrientationCamera === undefined) { webVROptions.createDeviceOrientationCamera = true; } if (webVROptions.laserToggle === undefined) { webVROptions.laserToggle = true; } if (webVROptions.defaultHeight === undefined) { webVROptions.defaultHeight = 1.7; } if (webVROptions.useCustomVRButton) { this._useCustomVRButton = true; if (webVROptions.customVRButton) { this._btnVR = webVROptions.customVRButton; } } if (webVROptions.rayLength) { this._rayLength = webVROptions.rayLength; } this._defaultHeight = webVROptions.defaultHeight; if (webVROptions.positionScale) { this._rayLength *= webVROptions.positionScale; this._defaultHeight *= webVROptions.positionScale; } this._hasEnteredVR = false; // Set position if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position.clone(); } else { this._position = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"](0, this._defaultHeight, 0); } // Set non-vr camera if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) { this._deviceOrientationCamera = new _Cameras_deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_5__["DeviceOrientationCamera"]("deviceOrientationVRHelper", this._position.clone(), scene); // Copy data from existing camera if (this._scene.activeCamera) { this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ; this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ; // Set rotation from previous camera if (this._scene.activeCamera instanceof _Cameras_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"] && this._scene.activeCamera.rotation) { var targetCamera = this._scene.activeCamera; if (targetCamera.rotationQuaternion) { this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion); } else { this._deviceOrientationCamera.rotationQuaternion.copyFrom(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z)); } this._deviceOrientationCamera.rotation = targetCamera.rotation.clone(); } } this._scene.activeCamera = this._deviceOrientationCamera; if (this._inputElement) { this._scene.activeCamera.attachControl(this._inputElement); } } else { this._existingCamera = this._scene.activeCamera; } if (this.webVROptions.useXR && navigator.xr) { // force-check XR session support _XR_webXRSessionManager__WEBPACK_IMPORTED_MODULE_30__["WebXRSessionManager"].IsSessionSupportedAsync("immersive-vr").then(function (supported) { if (supported) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log("Using WebXR. It is recommended to use the WebXRDefaultExperience directly"); // it is possible to use XR, let's do it! scene.createDefaultXRExperienceAsync({ floorMeshes: webVROptions.floorMeshes || [] }).then(function (xr) { _this.xr = xr; // connect observables _this.xrTestDone = true; _this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.xr.baseExperience.camera; }, scene); _this.xr.baseExperience.onStateChangedObservable.add(function (state) { // support for entering / exiting switch (state) { case _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__["WebXRState"].ENTERING_XR: _this.onEnteringVRObservable.notifyObservers(_this); if (!_this._interactionsEnabled) { _this.xr.pointerSelection.detach(); } _this.xr.pointerSelection.displayLaserPointer = _this._displayLaserPointer; break; case _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__["WebXRState"].EXITING_XR: _this.onExitingVRObservable.notifyObservers(_this); // resize to update width and height when exiting vr exits fullscreen _this._scene.getEngine().resize(); break; case _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__["WebXRState"].IN_XR: _this._hasEnteredVR = true; break; case _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__["WebXRState"].NOT_IN_XR: _this._hasEnteredVR = false; break; } }); }); } else { // XR not supported (thou exists), continue WebVR init _this.completeVRInit(scene, webVROptions); } }); } else { // no XR, continue init synchronous this.completeVRInit(scene, webVROptions); } } Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", { /** Return this.onEnteringVRObservable * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly */ get: function () { return this.onEnteringVRObservable; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", { /** Return this.onExitingVRObservable * Note: This one is for backward compatibility. Please use onExitingVRObservable directly */ get: function () { return this.onExitingVRObservable; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", { /** Return this.onControllerMeshLoadedObservable * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly */ get: function () { return this.onControllerMeshLoadedObservable; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", { /** * The mesh used to display where the user is going to teleport. */ get: function () { return this._teleportationTarget; }, /** * Sets the mesh to be used to display where the user is going to teleport. */ set: function (value) { if (value) { value.name = "teleportationTarget"; this._isDefaultTeleportationTarget = false; this._teleportationTarget = value; } }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", { /** * The mesh used to display where the user is selecting, this mesh will be cloned and set as the gazeTracker for the left and right controller * when set bakeCurrentTransformIntoVertices will be called on the mesh. * See https://doc.babylonjs.com/resources/baking_transformations */ get: function () { return this._cameraGazer._gazeTracker; }, set: function (value) { if (value) { // Dispose of existing meshes if (this._cameraGazer._gazeTracker) { this._cameraGazer._gazeTracker.dispose(); } if (this._leftController && this._leftController._gazeTracker) { this._leftController._gazeTracker.dispose(); } if (this._rightController && this._rightController._gazeTracker) { this._rightController._gazeTracker.dispose(); } // Set and create gaze trackers on head and controllers this._cameraGazer._gazeTracker = value; this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices(); this._cameraGazer._gazeTracker.isPickable = false; this._cameraGazer._gazeTracker.isVisible = false; this._cameraGazer._gazeTracker.name = "gazeTracker"; if (this._leftController) { this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); } if (this._rightController) { this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker"); } } }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", { /** * The gaze tracking mesh corresponding to the left controller */ get: function () { if (this._leftController) { return this._leftController._gazeTracker; } return null; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", { /** * The gaze tracking mesh corresponding to the right controller */ get: function () { if (this._rightController) { return this._rightController._gazeTracker; } return null; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", { /** * If the ray of the gaze should be displayed. */ get: function () { return this._displayGaze; }, /** * Sets if the ray of the gaze should be displayed. */ set: function (value) { this._displayGaze = value; if (!value) { this._cameraGazer._gazeTracker.isVisible = false; if (this._leftController) { this._leftController._gazeTracker.isVisible = false; } if (this._rightController) { this._rightController._gazeTracker.isVisible = false; } } }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", { /** * If the ray of the LaserPointer should be displayed. */ get: function () { return this._displayLaserPointer; }, /** * Sets if the ray of the LaserPointer should be displayed. */ set: function (value) { this._displayLaserPointer = value; if (!value) { if (this._rightController) { this._rightController._deactivatePointer(); this._rightController._gazeTracker.isVisible = false; } if (this._leftController) { this._leftController._deactivatePointer(); this._leftController._gazeTracker.isVisible = false; } } else { if (this._rightController) { this._rightController._activatePointer(); } if (this._leftController) { this._leftController._activatePointer(); } } }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", { /** * The deviceOrientationCamera used as the camera when not in VR. */ get: function () { return this._deviceOrientationCamera; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", { /** * Based on the current WebVR support, returns the current VR camera used. */ get: function () { if (this._webVRready) { return this._webVRCamera; } else { return this._scene.activeCamera; } }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", { /** * The webVRCamera which is used when in VR. */ get: function () { return this._webVRCamera; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", { /** * The deviceOrientationCamera that is used as a fallback when vr device is not connected. */ get: function () { return this._vrDeviceOrientationCamera; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "vrButton", { /** * The html button that is used to trigger entering into VR. */ get: function () { return this._btnVR; }, enumerable: false, configurable: true }); Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", { get: function () { var result = this._cameraGazer._teleportationRequestInitiated || (this._leftController !== null && this._leftController._teleportationRequestInitiated) || (this._rightController !== null && this._rightController._teleportationRequestInitiated); return result; }, enumerable: false, configurable: true }); VRExperienceHelper.prototype.completeVRInit = function (scene, webVROptions) { var _this = this; this.xrTestDone = true; // Create VR cameras if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { if (webVROptions.useMultiview) { if (!webVROptions.vrDeviceOrientationCameraMetrics) { webVROptions.vrDeviceOrientationCameraMetrics = _Cameras_VR_vrCameraMetrics__WEBPACK_IMPORTED_MODULE_23__["VRCameraMetrics"].GetDefault(); } webVROptions.vrDeviceOrientationCameraMetrics.multiviewEnabled = true; } this._vrDeviceOrientationCamera = new _Cameras_VR_vrDeviceOrientationFreeCamera__WEBPACK_IMPORTED_MODULE_6__["VRDeviceOrientationFreeCamera"]("VRDeviceOrientationVRHelper", this._position, this._scene, true, webVROptions.vrDeviceOrientationCameraMetrics); this._vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; } this._webVRCamera = new _Cameras_VR_webVRCamera__WEBPACK_IMPORTED_MODULE_7__["WebVRFreeCamera"]("WebVRHelper", this._position, this._scene, webVROptions); this._webVRCamera.useStandingMatrix(); this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene); // Create default button if (!this._useCustomVRButton) { this._btnVR = document.createElement("BUTTON"); this._btnVR.className = "babylonVRicon"; this._btnVR.id = "babylonVRiconbtn"; this._btnVR.title = "Click to switch to VR"; var url = !window.SVGSVGElement ? "https://cdn.babylonjs.com/Assets/vrButton.png" : "data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A"; var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(" + url + "); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }"; css += ".babylonVRicon.vrdisplaypresenting { display: none; }"; // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR) // css += ".babylonVRicon.vrdisplaysupported { }"; // css += ".babylonVRicon.vrdisplayready { }"; // css += ".babylonVRicon.vrdisplayrequesting { }"; var style = document.createElement('style'); style.appendChild(document.createTextNode(css)); document.getElementsByTagName('head')[0].appendChild(style); this.moveButtonToBottomRight(); } // VR button click event if (this._btnVR) { this._btnVR.addEventListener("click", function () { if (!_this.isInVRMode) { _this.enterVR(); } else { _this._scene.getEngine().disableVR(); } }); } // Window events var hostWindow = this._scene.getEngine().getHostWindow(); if (!hostWindow) { return; } hostWindow.addEventListener("resize", this._onResize); document.addEventListener("fullscreenchange", this._onFullscreenChange, false); document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false); document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false); document.addEventListener("msfullscreenchange", this._onFullscreenChange, false); document.onmsfullscreenchange = this._onFullscreenChange; // Display vr button when headset is connected if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) { this.displayVRButton(); } else { this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) { if (e.vrDisplay) { _this.displayVRButton(); } }); } // Exiting VR mode using 'ESC' key on desktop this._onKeyDown = function (event) { if (event.keyCode === 27 && _this.isInVRMode) { _this.exitVR(); } }; document.addEventListener("keydown", this._onKeyDown); // Exiting VR mode double tapping the touch screen this._scene.onPrePointerObservable.add(function () { if (_this._hasEnteredVR && _this.exitVROnDoubleTap) { _this.exitVR(); if (_this._fullscreenVRpresenting) { _this._scene.getEngine().exitFullscreen(); } } }, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERDOUBLETAP, false); // Listen for WebVR display changes this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); }; this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); }; this._onVRRequestPresentStart = function () { _this._webVRrequesting = true; _this.updateButtonVisibility(); }; this._onVRRequestPresentComplete = function () { _this._webVRrequesting = false; _this.updateButtonVisibility(); }; scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged); scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart); scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete); hostWindow.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); scene.onDisposeObservable.add(function () { _this.dispose(); }); // Gamepad connection events this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); }); this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected); this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected); this.updateButtonVisibility(); //create easing functions this._circleEase = new _Animations_easing__WEBPACK_IMPORTED_MODULE_21__["CircleEase"](); this._circleEase.setEasingMode(_Animations_easing__WEBPACK_IMPORTED_MODULE_21__["EasingFunction"].EASINGMODE_EASEINOUT); this._teleportationEasing = this._circleEase; // Allow clicking in the vrDeviceOrientationCamera scene.onPointerObservable.add(function (e) { if (_this._interactionsEnabled) { if (scene.activeCamera === _this.vrDeviceOrientationCamera && e.event.pointerType === "mouse") { if (e.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERDOWN) { _this._cameraGazer._selectionPointerDown(); } else if (e.type === _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_8__["PointerEventTypes"].POINTERUP) { _this._cameraGazer._selectionPointerUp(); } } } }); if (this.webVROptions.floorMeshes) { this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes }); } }; // Raised when one of the controller has loaded successfully its associated default mesh VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) { if (this._leftController && this._leftController.webVRController == webVRController) { if (webVRController.mesh) { this._leftController._setLaserPointerParent(webVRController.mesh); } } if (this._rightController && this._rightController.webVRController == webVRController) { if (webVRController.mesh) { this._rightController._setLaserPointerParent(webVRController.mesh); } } try { this.onControllerMeshLoadedObservable.notifyObservers(webVRController); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onControllerMeshLoaded: " + err); } }; Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", { /** * Gets a value indicating if we are currently in VR mode. */ get: function () { return (this.xr && this.webVROptions.useXR && this.xr.baseExperience.state === _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__["WebXRState"].IN_XR) || (this._webVRpresenting || this._fullscreenVRpresenting); }, enumerable: false, configurable: true }); VRExperienceHelper.prototype.onVrDisplayPresentChange = function () { var vrDisplay = this._scene.getEngine().getVRDevice(); if (vrDisplay) { var wasPresenting = this._webVRpresenting; this._webVRpresenting = vrDisplay.isPresenting; if (wasPresenting && !this._webVRpresenting) { this.exitVR(); } } else { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?'); } this.updateButtonVisibility(); }; VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) { this._webVRsupported = eventArgs.vrSupported; this._webVRready = !!eventArgs.vrDisplay; this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting; this.updateButtonVisibility(); }; VRExperienceHelper.prototype.moveButtonToBottomRight = function () { if (this._inputElement && !this._useCustomVRButton && this._btnVR) { var rect = this._inputElement.getBoundingClientRect(); this._btnVR.style.top = rect.top + rect.height - 70 + "px"; this._btnVR.style.left = rect.left + rect.width - 100 + "px"; } }; VRExperienceHelper.prototype.displayVRButton = function () { if (!this._useCustomVRButton && !this._btnVRDisplayed && this._btnVR) { document.body.appendChild(this._btnVR); this._btnVRDisplayed = true; } }; VRExperienceHelper.prototype.updateButtonVisibility = function () { if (!this._btnVR || this._useCustomVRButton) { return; } this._btnVR.className = "babylonVRicon"; if (this.isInVRMode) { this._btnVR.className += " vrdisplaypresenting"; } else { if (this._webVRready) { this._btnVR.className += " vrdisplayready"; } if (this._webVRsupported) { this._btnVR.className += " vrdisplaysupported"; } if (this._webVRrequesting) { this._btnVR.className += " vrdisplayrequesting"; } } }; /** * Attempt to enter VR. If a headset is connected and ready, will request present on that. * Otherwise, will use the fullscreen API. */ VRExperienceHelper.prototype.enterVR = function () { var _this = this; if (this.xr) { this.xr.baseExperience.enterXRAsync("immersive-vr", "local-floor", this.xr.renderTarget); return; } if (this.onEnteringVRObservable) { try { this.onEnteringVRObservable.notifyObservers(this); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onEnteringVR: " + err); } } if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position.clone(); if (this.vrDeviceOrientationCamera) { this.vrDeviceOrientationCamera.rotation = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles(); this.vrDeviceOrientationCamera.angularSensibility = 2000; } if (this.webVRCamera) { var currentYRotation = this.webVRCamera.deviceRotationQuaternion.toEulerAngles().y; var desiredYRotation = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this._scene.activeCamera.getWorldMatrix().getRotationMatrix()).toEulerAngles().y; var delta = desiredYRotation - currentYRotation; var currentGlobalRotation = this.webVRCamera.rotationQuaternion.toEulerAngles().y; this.webVRCamera.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromEulerAngles(0, currentGlobalRotation + delta, 0); } // make sure that we return to the last active camera this._existingCamera = this._scene.activeCamera; // Remove and cache angular sensability to avoid camera rotation when in VR if (this._existingCamera.angularSensibilityX) { this._cachedAngularSensibility.angularSensibilityX = this._existingCamera.angularSensibilityX; this._existingCamera.angularSensibilityX = Number.MAX_VALUE; } if (this._existingCamera.angularSensibilityY) { this._cachedAngularSensibility.angularSensibilityY = this._existingCamera.angularSensibilityY; this._existingCamera.angularSensibilityY = Number.MAX_VALUE; } if (this._existingCamera.angularSensibility) { this._cachedAngularSensibility.angularSensibility = this._existingCamera.angularSensibility; this._existingCamera.angularSensibility = Number.MAX_VALUE; } } if (this._webVRrequesting) { return; } // If WebVR is supported and a headset is connected if (this._webVRready) { if (!this._webVRpresenting) { this._scene.getEngine().onVRRequestPresentComplete.addOnce(function (result) { _this.onAfterEnteringVRObservable.notifyObservers({ success: result }); }); this._webVRCamera.position = this._position; this._scene.activeCamera = this._webVRCamera; } } else if (this._vrDeviceOrientationCamera) { this._vrDeviceOrientationCamera.position = this._position; if (this._scene.activeCamera) { this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ; } this._scene.activeCamera = this._vrDeviceOrientationCamera; this._scene.getEngine().enterFullscreen(this.requestPointerLockOnFullScreen); this.updateButtonVisibility(); this._vrDeviceOrientationCamera.onViewMatrixChangedObservable.addOnce(function () { _this.onAfterEnteringVRObservable.notifyObservers({ success: true }); }); } if (this._scene.activeCamera && this._inputElement) { this._scene.activeCamera.attachControl(this._inputElement); } if (this._interactionsEnabled) { this._scene.registerBeforeRender(this.beforeRender); } if (this._displayLaserPointer) { [this._leftController, this._rightController].forEach(function (controller) { if (controller) { controller._activatePointer(); } }); } this._hasEnteredVR = true; }; /** * Attempt to exit VR, or fullscreen. */ VRExperienceHelper.prototype.exitVR = function () { if (this.xr) { this.xr.baseExperience.exitXRAsync(); return; } if (this._hasEnteredVR) { if (this.onExitingVRObservable) { try { this.onExitingVRObservable.notifyObservers(this); } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error in your custom logic onExitingVR: " + err); } } if (this._webVRpresenting) { this._scene.getEngine().disableVR(); } if (this._scene.activeCamera) { this._position = this._scene.activeCamera.position.clone(); } if (this.vrDeviceOrientationCamera) { this.vrDeviceOrientationCamera.angularSensibility = Number.MAX_VALUE; } if (this._deviceOrientationCamera) { this._deviceOrientationCamera.position = this._position; this._scene.activeCamera = this._deviceOrientationCamera; // Restore angular sensibility if (this._cachedAngularSensibility.angularSensibilityX) { this._deviceOrientationCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; this._cachedAngularSensibility.angularSensibilityX = null; } if (this._cachedAngularSensibility.angularSensibilityY) { this._deviceOrientationCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; this._cachedAngularSensibility.angularSensibilityY = null; } if (this._cachedAngularSensibility.angularSensibility) { this._deviceOrientationCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; this._cachedAngularSensibility.angularSensibility = null; } } else if (this._existingCamera) { this._existingCamera.position = this._position; this._scene.activeCamera = this._existingCamera; if (this._inputElement) { this._scene.activeCamera.attachControl(this._inputElement); } // Restore angular sensibility if (this._cachedAngularSensibility.angularSensibilityX) { this._existingCamera.angularSensibilityX = this._cachedAngularSensibility.angularSensibilityX; this._cachedAngularSensibility.angularSensibilityX = null; } if (this._cachedAngularSensibility.angularSensibilityY) { this._existingCamera.angularSensibilityY = this._cachedAngularSensibility.angularSensibilityY; this._cachedAngularSensibility.angularSensibilityY = null; } if (this._cachedAngularSensibility.angularSensibility) { this._existingCamera.angularSensibility = this._cachedAngularSensibility.angularSensibility; this._cachedAngularSensibility.angularSensibility = null; } } this.updateButtonVisibility(); if (this._interactionsEnabled) { this._scene.unregisterBeforeRender(this.beforeRender); this._cameraGazer._gazeTracker.isVisible = false; if (this._leftController) { this._leftController._gazeTracker.isVisible = false; } if (this._rightController) { this._rightController._gazeTracker.isVisible = false; } } // resize to update width and height when exiting vr exits fullscreen this._scene.getEngine().resize(); [this._leftController, this._rightController].forEach(function (controller) { if (controller) { controller._deactivatePointer(); } }); this._hasEnteredVR = false; // Update engine state to re enable non-vr camera input var engine = this._scene.getEngine(); if (engine._onVrDisplayPresentChange) { engine._onVrDisplayPresentChange(); } } }; Object.defineProperty(VRExperienceHelper.prototype, "position", { /** * The position of the vr experience helper. */ get: function () { return this._position; }, /** * Sets the position of the vr experience helper. */ set: function (value) { this._position = value; if (this._scene.activeCamera) { this._scene.activeCamera.position = value; } }, enumerable: false, configurable: true }); /** * Enables controllers and user interactions such as selecting and object or clicking on an object. */ VRExperienceHelper.prototype.enableInteractions = function () { var _this = this; if (!this._interactionsEnabled) { this._interactionsRequested = true; // in XR it is enabled by default, but just to make sure, re-attach if (this.xr) { if (this.xr.baseExperience.state === _XR_webXRTypes__WEBPACK_IMPORTED_MODULE_31__["WebXRState"].IN_XR) { this.xr.pointerSelection.attach(); } return; } if (this._leftController) { this._enableInteractionOnController(this._leftController); } if (this._rightController) { this._enableInteractionOnController(this._rightController); } this.raySelectionPredicate = function (mesh) { return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName); }; this.meshSelectionPredicate = function () { return true; }; this._raySelectionPredicate = function (mesh) { if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1 && mesh.name.indexOf("teleportationTarget") === -1 && mesh.name.indexOf("torusTeleportation") === -1)) { return _this.raySelectionPredicate(mesh); } return false; }; this._interactionsEnabled = true; } }; Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", { get: function () { return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer); }, enumerable: false, configurable: true }); VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) { for (var i = 0; i < this._floorMeshesCollection.length; i++) { if (this._floorMeshesCollection[i].id === mesh.id) { return true; } } if (this._floorMeshName && mesh.name === this._floorMeshName) { return true; } return false; }; /** * Adds a floor mesh to be used for teleportation. * @param floorMesh the mesh to be used for teleportation. */ VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) { if (!this._floorMeshesCollection) { return; } if (this._floorMeshesCollection.indexOf(floorMesh) > -1) { return; } this._floorMeshesCollection.push(floorMesh); }; /** * Removes a floor mesh from being used for teleportation. * @param floorMesh the mesh to be removed. */ VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) { if (!this._floorMeshesCollection) { return; } var meshIndex = this._floorMeshesCollection.indexOf(floorMesh); if (meshIndex !== -1) { this._floorMeshesCollection.splice(meshIndex, 1); } }; /** * Enables interactions and teleportation using the VR controllers and gaze. * @param vrTeleportationOptions options to modify teleportation behavior. */ VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) { var _this = this; if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; } if (!this._teleportationInitialized) { this._teleportationRequested = true; this.enableInteractions(); if (this.webVROptions.useXR && (vrTeleportationOptions.floorMeshes || vrTeleportationOptions.floorMeshName)) { var floorMeshes = vrTeleportationOptions.floorMeshes || []; if (!floorMeshes.length) { var floorMesh = this._scene.getMeshByName(vrTeleportationOptions.floorMeshName); if (floorMesh) { floorMeshes.push(floorMesh); } } if (this.xr) { floorMeshes.forEach(function (mesh) { _this.xr.teleportation.addFloorMesh(mesh); }); if (!this.xr.teleportation.attached) { this.xr.teleportation.attach(); } return; } else if (!this.xrTestDone) { var waitForXr_1 = function () { if (_this.xrTestDone) { _this._scene.unregisterBeforeRender(waitForXr_1); if (_this.xr) { if (!_this.xr.teleportation.attached) { _this.xr.teleportation.attach(); } } else { _this.enableTeleportation(vrTeleportationOptions); } } }; this._scene.registerBeforeRender(waitForXr_1); return; } } if (vrTeleportationOptions.floorMeshName) { this._floorMeshName = vrTeleportationOptions.floorMeshName; } if (vrTeleportationOptions.floorMeshes) { this._floorMeshesCollection = vrTeleportationOptions.floorMeshes; } if (vrTeleportationOptions.teleportationMode) { this._teleportationMode = vrTeleportationOptions.teleportationMode; } if (vrTeleportationOptions.teleportationTime && vrTeleportationOptions.teleportationTime > 0) { this._teleportationTime = vrTeleportationOptions.teleportationTime; } if (vrTeleportationOptions.teleportationSpeed && vrTeleportationOptions.teleportationSpeed > 0) { this._teleportationSpeed = vrTeleportationOptions.teleportationSpeed; } if (vrTeleportationOptions.easingFunction !== undefined) { this._teleportationEasing = vrTeleportationOptions.easingFunction; } if (this._leftController != null) { this._enableTeleportationOnController(this._leftController); } if (this._rightController != null) { this._enableTeleportationOnController(this._rightController); } // Creates an image processing post process for the vignette not relying // on the main scene configuration for image processing to reduce setup and spaces // (gamma/linear) conflicts. var imageProcessingConfiguration = new _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_17__["ImageProcessingConfiguration"](); imageProcessingConfiguration.vignetteColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color4"](0, 0, 0, 0); imageProcessingConfiguration.vignetteEnabled = true; this._postProcessMove = new _PostProcesses_imageProcessingPostProcess__WEBPACK_IMPORTED_MODULE_20__["ImageProcessingPostProcess"]("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration); this._webVRCamera.detachPostProcess(this._postProcessMove); this._teleportationInitialized = true; if (this._isDefaultTeleportationTarget) { this._createTeleportationCircles(); this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor); } } }; VRExperienceHelper.prototype._enableInteractionOnController = function (controller) { var _this = this; var controllerMesh = controller.webVRController.mesh; if (controllerMesh) { controller._interactionsEnabled = true; if (this.isInVRMode && this._displayLaserPointer) { controller._activatePointer(); } if (this.webVROptions.laserToggle) { controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) { // Enabling / disabling laserPointer if (_this._displayLaserPointer && stateObject.value === 1) { if (controller._activePointer) { controller._deactivatePointer(); } else { controller._activatePointer(); } if (_this.displayGaze) { controller._gazeTracker.isVisible = controller._activePointer; } } }); } controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) { var gazer = controller; if (_this._noControllerIsActive) { gazer = _this._cameraGazer; } if (!gazer._pointerDownOnMeshAsked) { if (stateObject.value > _this._padSensibilityUp) { gazer._selectionPointerDown(); } } else if (stateObject.value < _this._padSensibilityDown) { gazer._selectionPointerUp(); } }); } }; VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) { // Dont teleport if another gaze already requested teleportation if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) { return; } if (!gazer._teleportationRequestInitiated) { if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) { gazer._activatePointer(); gazer._teleportationRequestInitiated = true; } } else { // Listening to the proper controller values changes to confirm teleportation if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) { if (this._teleportActive) { this.teleportCamera(this._haloCenter); } gazer._teleportationRequestInitiated = false; } } }; VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) { // Only rotate when user is not currently selecting a teleportation location if (gazer._teleportationRequestInitiated) { return; } if (!gazer._rotationLeftAsked) { if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) { gazer._rotationLeftAsked = true; if (this._rotationAllowed) { this._rotateCamera(false); } } } else { if (stateObject.x > -this._padSensibilityDown) { gazer._rotationLeftAsked = false; } } if (!gazer._rotationRightAsked) { if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) { gazer._rotationRightAsked = true; if (this._rotationAllowed) { this._rotateCamera(true); } } } else { if (stateObject.x < this._padSensibilityDown) { gazer._rotationRightAsked = false; } } }; VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) { // Only teleport backwards when user is not currently selecting a teleportation location if (gazer._teleportationRequestInitiated) { return; } // Teleport backwards if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) { if (!gazer._teleportationBackRequestInitiated) { if (!this.currentVRCamera) { return; } // Get rotation and position of the current camera var rotation = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix()); var position = this.currentVRCamera.position; // If the camera has device position, use that instead if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) { rotation = this.currentVRCamera.deviceRotationQuaternion; position = this.currentVRCamera.devicePosition; } // Get matrix with only the y rotation of the device rotation rotation.toEulerAnglesToRef(this._workingVector); this._workingVector.z = 0; this._workingVector.x = 0; _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion); this._workingQuaternion.toRotationMatrix(this._workingMatrix); // Rotate backwards ray by device rotation to cast at the ground behind the user _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector); // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff var ray = new _Culling_ray__WEBPACK_IMPORTED_MODULE_16__["Ray"](position, this._workingVector); var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) { this.teleportCamera(hit.pickedPoint); } gazer._teleportationBackRequestInitiated = true; } } else { gazer._teleportationBackRequestInitiated = false; } }; VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) { var _this = this; var controllerMesh = controller.webVRController.mesh; if (controllerMesh) { if (!controller._interactionsEnabled) { this._enableInteractionOnController(controller); } controller._interactionsEnabled = true; controller._teleportationEnabled = true; if (controller.webVRController.controllerType === _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_12__["PoseEnabledControllerType"].VIVE) { controller._dpadPressed = false; controller.webVRController.onPadStateChangedObservable.add(function (stateObject) { controller._dpadPressed = stateObject.pressed; if (!controller._dpadPressed) { controller._rotationLeftAsked = false; controller._rotationRightAsked = false; controller._teleportationBackRequestInitiated = false; } }); } controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) { if (_this.teleportationEnabled) { _this._checkTeleportBackwards(stateObject, controller); _this._checkTeleportWithRay(stateObject, controller); } _this._checkRotate(stateObject, controller); }); } }; VRExperienceHelper.prototype._createTeleportationCircles = function () { this._teleportationTarget = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__["Mesh"].CreateGround("teleportationTarget", 2, 2, 2, this._scene); this._teleportationTarget.isPickable = false; var length = 512; var dynamicTexture = new _Materials_Textures_dynamicTexture__WEBPACK_IMPORTED_MODULE_19__["DynamicTexture"]("DynamicTexture", length, this._scene, true); dynamicTexture.hasAlpha = true; var context = dynamicTexture.getContext(); var centerX = length / 2; var centerY = length / 2; var radius = 200; context.beginPath(); context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false); context.fillStyle = this._teleportationFillColor; context.fill(); context.lineWidth = 10; context.strokeStyle = this._teleportationBorderColor; context.stroke(); context.closePath(); dynamicTexture.update(); var teleportationCircleMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_18__["StandardMaterial"]("TextPlaneMaterial", this._scene); teleportationCircleMaterial.diffuseTexture = dynamicTexture; this._teleportationTarget.material = teleportationCircleMaterial; var torus = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_15__["Mesh"].CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false); torus.isPickable = false; torus.parent = this._teleportationTarget; var animationInnerCircle = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationInnerCircle", "position.y", 30, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CYCLE); var keys = []; keys.push({ frame: 0, value: 0 }); keys.push({ frame: 30, value: 0.4 }); keys.push({ frame: 60, value: 0 }); animationInnerCircle.setKeys(keys); var easingFunction = new _Animations_easing__WEBPACK_IMPORTED_MODULE_21__["SineEase"](); easingFunction.setEasingMode(_Animations_easing__WEBPACK_IMPORTED_MODULE_21__["EasingFunction"].EASINGMODE_EASEINOUT); animationInnerCircle.setEasingFunction(easingFunction); torus.animations = []; torus.animations.push(animationInnerCircle); this._scene.beginAnimation(torus, 0, 60, true); this._hideTeleportationTarget(); }; VRExperienceHelper.prototype._displayTeleportationTarget = function () { this._teleportActive = true; if (this._teleportationInitialized) { this._teleportationTarget.isVisible = true; if (this._isDefaultTeleportationTarget) { this._teleportationTarget.getChildren()[0].isVisible = true; } } }; VRExperienceHelper.prototype._hideTeleportationTarget = function () { this._teleportActive = false; if (this._teleportationInitialized) { this._teleportationTarget.isVisible = false; if (this._isDefaultTeleportationTarget) { this._teleportationTarget.getChildren()[0].isVisible = false; } } }; VRExperienceHelper.prototype._rotateCamera = function (right) { var _this = this; if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { return; } if (right) { this._rotationAngle++; } else { this._rotationAngle--; } this.currentVRCamera.animations = []; var target = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Quaternion"].FromRotationMatrix(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Matrix"].RotationY(Math.PI / 4 * this._rotationAngle)); var animationRotation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationRotation", "rotationQuaternion", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_QUATERNION, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var animationRotationKeys = []; animationRotationKeys.push({ frame: 0, value: this.currentVRCamera.rotationQuaternion }); animationRotationKeys.push({ frame: 6, value: target }); animationRotation.setKeys(animationRotationKeys); animationRotation.setEasingFunction(this._circleEase); this.currentVRCamera.animations.push(animationRotation); this._postProcessMove.animations = []; var animationPP = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationPP", "vignetteWeight", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteWeightKeys = []; vignetteWeightKeys.push({ frame: 0, value: 0 }); vignetteWeightKeys.push({ frame: 3, value: 4 }); vignetteWeightKeys.push({ frame: 6, value: 0 }); animationPP.setKeys(vignetteWeightKeys); animationPP.setEasingFunction(this._circleEase); this._postProcessMove.animations.push(animationPP); var animationPP2 = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationPP2", "vignetteStretch", 90, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteStretchKeys = []; vignetteStretchKeys.push({ frame: 0, value: 0 }); vignetteStretchKeys.push({ frame: 3, value: 10 }); vignetteStretchKeys.push({ frame: 6, value: 0 }); animationPP2.setKeys(vignetteStretchKeys); animationPP2.setEasingFunction(this._circleEase); this._postProcessMove.animations.push(animationPP2); this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; this._postProcessMove.samples = 4; this._webVRCamera.attachPostProcess(this._postProcessMove); this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () { _this._webVRCamera.detachPostProcess(_this._postProcessMove); }); this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1); }; VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) { if (hit.pickedPoint) { if (gazer._teleportationRequestInitiated) { this._displayTeleportationTarget(); this._haloCenter.copyFrom(hit.pickedPoint); this._teleportationTarget.position.copyFrom(hit.pickedPoint); } var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray); if (pickNormal) { var axis1 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_29__["Axis"].Y, pickNormal); var axis2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(pickNormal, axis1); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation); } this._teleportationTarget.position.y += 0.1; } }; /** * Teleports the users feet to the desired location * @param location The location where the user's feet should be placed */ VRExperienceHelper.prototype.teleportCamera = function (location) { var _this = this; if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { return; } // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the // offset of the headset from the anchor. if (this.webVRCamera.leftCamera) { this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition); this._workingVector.subtractInPlace(this.webVRCamera.position); location.subtractToRef(this._workingVector, this._workingVector); } else { this._workingVector.copyFrom(location); } // Add height to account for user's height offset if (this.isInVRMode) { this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor; } else { this._workingVector.y += this._defaultHeight; } this.onBeforeCameraTeleport.notifyObservers(this._workingVector); // Animations FPS var FPS = 90; var speedRatio, lastFrame; if (this._teleportationMode == VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED) { lastFrame = FPS; var dist = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Distance(this.currentVRCamera.position, this._workingVector); speedRatio = this._teleportationSpeed / dist; } else { // teleportationMode is TELEPORTATIONMODE_CONSTANTTIME lastFrame = Math.round(this._teleportationTime * FPS / 1000); speedRatio = 1; } // Create animation from the camera's position to the new location this.currentVRCamera.animations = []; var animationCameraTeleportation = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationCameraTeleportation", "position", FPS, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_VECTOR3, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var animationCameraTeleportationKeys = [{ frame: 0, value: this.currentVRCamera.position }, { frame: lastFrame, value: this._workingVector } ]; animationCameraTeleportation.setKeys(animationCameraTeleportationKeys); animationCameraTeleportation.setEasingFunction(this._teleportationEasing); this.currentVRCamera.animations.push(animationCameraTeleportation); this._postProcessMove.animations = []; // Calculate the mid frame for vignette animations var midFrame = Math.round(lastFrame / 2); var animationPP = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationPP", "vignetteWeight", FPS, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteWeightKeys = []; vignetteWeightKeys.push({ frame: 0, value: 0 }); vignetteWeightKeys.push({ frame: midFrame, value: 8 }); vignetteWeightKeys.push({ frame: lastFrame, value: 0 }); animationPP.setKeys(vignetteWeightKeys); this._postProcessMove.animations.push(animationPP); var animationPP2 = new _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"]("animationPP2", "vignetteStretch", FPS, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONTYPE_FLOAT, _Animations_animation__WEBPACK_IMPORTED_MODULE_22__["Animation"].ANIMATIONLOOPMODE_CONSTANT); var vignetteStretchKeys = []; vignetteStretchKeys.push({ frame: 0, value: 0 }); vignetteStretchKeys.push({ frame: midFrame, value: 10 }); vignetteStretchKeys.push({ frame: lastFrame, value: 0 }); animationPP2.setKeys(vignetteStretchKeys); this._postProcessMove.animations.push(animationPP2); this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0; this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0; this._webVRCamera.attachPostProcess(this._postProcessMove); this._scene.beginAnimation(this._postProcessMove, 0, lastFrame, false, speedRatio, function () { _this._webVRCamera.detachPostProcess(_this._postProcessMove); }); this._scene.beginAnimation(this.currentVRCamera, 0, lastFrame, false, speedRatio, function () { _this.onAfterCameraTeleport.notifyObservers(_this._workingVector); }); this._hideTeleportationTarget(); }; VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) { if (normal) { var angle = Math.acos(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Dot(normal, ray.direction)); if (angle < Math.PI / 2) { normal.scaleInPlace(-1); } } return normal; }; VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) { if (!(this.currentVRCamera instanceof _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_3__["FreeCamera"])) { return; } var ray = gazer._getForwardRay(this._rayLength); var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate); if (hit) { // Populate the controllers mesh that can be used for drag/drop if (gazer._laserPointer) { hit.originMesh = gazer._laserPointer.parent; } this._scene.simulatePointerMove(hit, { pointerId: gazer._id }); } gazer._currentHit = hit; // Moving the gazeTracker on the mesh face targetted if (hit && hit.pickedPoint) { if (this._displayGaze) { var multiplier = 1; gazer._gazeTracker.isVisible = true; if (gazer._isActionableMesh) { multiplier = 3; } if (this.updateGazeTrackerScale) { gazer._gazeTracker.scaling.x = hit.distance * multiplier; gazer._gazeTracker.scaling.y = hit.distance * multiplier; gazer._gazeTracker.scaling.z = hit.distance * multiplier; } var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray); // To avoid z-fighting var deltaFighting = 0.002; if (pickNormal) { var axis1 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_29__["Axis"].Y, pickNormal); var axis2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].Cross(pickNormal, axis1); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_9__["Vector3"].RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation); } gazer._gazeTracker.position.copyFrom(hit.pickedPoint); if (gazer._gazeTracker.position.x < 0) { gazer._gazeTracker.position.x += deltaFighting; } else { gazer._gazeTracker.position.x -= deltaFighting; } if (gazer._gazeTracker.position.y < 0) { gazer._gazeTracker.position.y += deltaFighting; } else { gazer._gazeTracker.position.y -= deltaFighting; } if (gazer._gazeTracker.position.z < 0) { gazer._gazeTracker.position.z += deltaFighting; } else { gazer._gazeTracker.position.z -= deltaFighting; } } // Changing the size of the laser pointer based on the distance from the targetted point gazer._updatePointerDistance(hit.distance); } else { gazer._updatePointerDistance(); gazer._gazeTracker.isVisible = false; } if (hit && hit.pickedMesh) { // The object selected is the floor, we're in a teleportation scenario if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) { // Moving the teleportation area to this targetted point //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) { this._notifySelectedMeshUnselected(gazer._currentMeshSelected); } gazer._currentMeshSelected = null; if (gazer._teleportationRequestInitiated) { this._moveTeleportationSelectorTo(hit, gazer, ray); } return; } // If not, we're in a selection scenario //this._teleportationAllowed = false; if (hit.pickedMesh !== gazer._currentMeshSelected) { if (this.meshSelectionPredicate(hit.pickedMesh)) { this.onNewMeshPicked.notifyObservers(hit); gazer._currentMeshSelected = hit.pickedMesh; if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) { this.changeGazeColor(this._pickedGazeColor); this.changeLaserColor(this._pickedLaserColor); gazer._isActionableMesh = true; } else { this.changeGazeColor(this._gazeColor); this.changeLaserColor(this._laserColor); gazer._isActionableMesh = false; } try { this.onNewMeshSelected.notifyObservers(hit.pickedMesh); var gazerAsControllerGazer = gazer; if (gazerAsControllerGazer.webVRController) { this.onMeshSelectedWithController.notifyObservers({ mesh: hit.pickedMesh, controller: gazerAsControllerGazer.webVRController }); } } catch (err) { _Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Error while raising onNewMeshSelected or onMeshSelectedWithController: " + err); } } else { this._notifySelectedMeshUnselected(gazer._currentMeshSelected); gazer._currentMeshSelected = null; this.changeGazeColor(this._gazeColor); this.changeLaserColor(this._laserColor); } } } else { this._notifySelectedMeshUnselected(gazer._currentMeshSelected); gazer._currentMeshSelected = null; //this._teleportationAllowed = false; this.changeGazeColor(this._gazeColor); this.changeLaserColor(this._laserColor); } }; VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) { if (mesh) { this.onSelectedMeshUnselected.notifyObservers(mesh); } }; /** * Permanently set new colors for the laser pointer * @param color the new laser color * @param pickedColor the new laser color when picked mesh detected */ VRExperienceHelper.prototype.setLaserColor = function (color, pickedColor) { if (pickedColor === void 0) { pickedColor = this._pickedLaserColor; } this._laserColor = color; this._pickedLaserColor = pickedColor; }; /** * Set lighting enabled / disabled on the laser pointer of both controllers * @param enabled should the lighting be enabled on the laser pointer */ VRExperienceHelper.prototype.setLaserLightingState = function (enabled) { if (enabled === void 0) { enabled = true; } if (this._leftController) { this._leftController._setLaserPointerLightingDisabled(!enabled); } if (this._rightController) { this._rightController._setLaserPointerLightingDisabled(!enabled); } }; /** * Permanently set new colors for the gaze pointer * @param color the new gaze color * @param pickedColor the new gaze color when picked mesh detected */ VRExperienceHelper.prototype.setGazeColor = function (color, pickedColor) { if (pickedColor === void 0) { pickedColor = this._pickedGazeColor; } this._gazeColor = color; this._pickedGazeColor = pickedColor; }; /** * Sets the color of the laser ray from the vr controllers. * @param color new color for the ray. */ VRExperienceHelper.prototype.changeLaserColor = function (color) { if (!this.updateControllerLaserColor) { return; } if (this._leftController) { this._leftController._setLaserPointerColor(color); } if (this._rightController) { this._rightController._setLaserPointerColor(color); } }; /** * Sets the color of the ray from the vr headsets gaze. * @param color new color for the ray. */ VRExperienceHelper.prototype.changeGazeColor = function (color) { if (!this.updateGazeTrackerColor) { return; } if (!this._cameraGazer._gazeTracker.material) { return; } this._cameraGazer._gazeTracker.material.emissiveColor = color; if (this._leftController) { this._leftController._gazeTracker.material.emissiveColor = color; } if (this._rightController) { this._rightController._gazeTracker.material.emissiveColor = color; } }; /** * Exits VR and disposes of the vr experience helper */ VRExperienceHelper.prototype.dispose = function () { if (this.isInVRMode) { this.exitVR(); } if (this._postProcessMove) { this._postProcessMove.dispose(); } if (this._webVRCamera) { this._webVRCamera.dispose(); } if (this._vrDeviceOrientationCamera) { this._vrDeviceOrientationCamera.dispose(); } if (!this._useCustomVRButton && this._btnVR && this._btnVR.parentNode) { document.body.removeChild(this._btnVR); } if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) { this._deviceOrientationCamera.dispose(); } if (this._cameraGazer) { this._cameraGazer.dispose(); } if (this._leftController) { this._leftController.dispose(); } if (this._rightController) { this._rightController.dispose(); } if (this._teleportationTarget) { this._teleportationTarget.dispose(); } if (this.xr) { this.xr.dispose(); } this._floorMeshesCollection = []; document.removeEventListener("keydown", this._onKeyDown); window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); window.removeEventListener("resize", this._onResize); document.removeEventListener("fullscreenchange", this._onFullscreenChange); document.removeEventListener("mozfullscreenchange", this._onFullscreenChange); document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange); document.removeEventListener("msfullscreenchange", this._onFullscreenChange); document.onmsfullscreenchange = null; this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged); this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart); this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete); window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange); this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected); this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected); this._scene.unregisterBeforeRender(this.beforeRender); }; /** * Gets the name of the VRExperienceHelper class * @returns "VRExperienceHelper" */ VRExperienceHelper.prototype.getClassName = function () { return "VRExperienceHelper"; }; /** * Time Constant Teleportation Mode */ VRExperienceHelper.TELEPORTATIONMODE_CONSTANTTIME = 0; /** * Speed Constant Teleportation Mode */ VRExperienceHelper.TELEPORTATIONMODE_CONSTANTSPEED = 1; return VRExperienceHelper; }()); /***/ }), /***/ "./Cameras/VR/webVRCamera.ts": /*!***********************************!*\ !*** ./Cameras/VR/webVRCamera.ts ***! \***********************************/ /*! exports provided: WebVRFreeCamera */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return WebVRFreeCamera; }); /* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js"); /* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts"); /* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Cameras/freeCamera */ "./Cameras/freeCamera.ts"); /* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts"); /* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts"); /* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts"); /* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts"); /* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../node */ "./node.ts"); /* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts"); /* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts"); /* harmony import */ var _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../PostProcesses/vrMultiviewToSingleviewPostProcess */ "./PostProcesses/vrMultiviewToSingleviewPostProcess.ts"); /* harmony import */ var _RigModes_webVRRigMode__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../RigModes/webVRRigMode */ "./Cameras/RigModes/webVRRigMode.ts"); /* harmony import */ var _Engines_Extensions_engine_webVR__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Engines/Extensions/engine.webVR */ "./Engines/Extensions/engine.webVR.ts"); // Side effect import to define the stereoscopic mode. // Side effect import to add webvr support to engine _node__WEBPACK_IMPORTED_MODULE_7__["Node"].AddNodeConstructor("WebVRFreeCamera", function (name, scene) { return function () { return new WebVRFreeCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); _node__WEBPACK_IMPORTED_MODULE_7__["Node"].AddNodeConstructor("WebVRGamepadCamera", function (name, scene) { return function () { return new WebVRFreeCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); }; }); /** * This represents a WebVR camera. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift. * @example https://doc.babylonjs.com/how_to/webvr_camera */ var WebVRFreeCamera = /** @class */ (function (_super) { Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WebVRFreeCamera, _super); /** * Instantiates a WebVRFreeCamera. * @param name The name of the WebVRFreeCamera * @param position The starting anchor position for the camera * @param scene The scene the camera belongs to * @param webVROptions a set of customizable options for the webVRCamera */ function WebVRFreeCamera(name, position, scene, webVROptions) { if (webVROptions === void 0) { webVROptions = {}; } var _this = _super.call(this, name, position, scene) || this; _this.webVROptions = webVROptions; /** * @hidden * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay */ _this._vrDevice = null; /** * The rawPose of the vrDevice. */ _this.rawPose = null; _this._specsVersion = "1.1"; _this._attached = false; _this._descendants = []; // Represents device position and rotation in room space. Should only be used to help calculate babylon space values _this._deviceRoomPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); /** @hidden */ _this._deviceRoomRotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity(); _this._standingMatrix = null; /** * Represents device position in babylon space. */ _this.devicePosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); /** * Represents device rotation in babylon space. */ _this.deviceRotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].Identity(); /** * The scale of the device to be used when translating from device space to babylon space. */ _this.deviceScaleFactor = 1; _this._deviceToWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); _this._worldToDevice = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); /** * References to the webVR controllers for the vrDevice. */ _this.controllers = []; /** * Emits an event when a controller is attached. */ _this.onControllersAttachedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Emits an event when a controller's mesh has been loaded; */ _this.onControllerMeshLoadedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); /** * Emits an event when the HMD's pose has been updated. */ _this.onPoseUpdatedFromDeviceObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"](); _this._poseSet = false; /** * If the rig cameras be used as parent instead of this camera. */ _this.rigParenting = true; _this._defaultHeight = undefined; _this._htmlElementAttached = null; _this._detachIfAttached = function () { var vrDisplay = _this.getEngine().getVRDevice(); if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) { _this.detachControl(_this._htmlElementAttached); } }; _this._workingVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); _this._oneVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].One(); _this._workingMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity(); _this._tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); _this._cache.position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(); if (webVROptions.defaultHeight) { _this._defaultHeight = webVROptions.defaultHeight; _this.position.y = _this._defaultHeight; } _this.minZ = 0.1; //legacy support - the compensation boolean was removed. if (arguments.length === 5) { _this.webVROptions = arguments[4]; } // default webVR options if (_this.webVROptions.trackPosition == undefined) { _this.webVROptions.trackPosition = true; } if (_this.webVROptions.controllerMeshes == undefined) { _this.webVROptions.controllerMeshes = true; } if (_this.webVROptions.defaultLightingOnControllers == undefined) { _this.webVROptions.defaultLightingOnControllers = true; } _this.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"](); if (_this.webVROptions && _this.webVROptions.positionScale) { _this.deviceScaleFactor = _this.webVROptions.positionScale; } //enable VR var engine = _this.getEngine(); _this._onVREnabled = function (success) { if (success) { _this.initControllers(); } }; engine.onVRRequestPresentComplete.add(_this._onVREnabled); engine.initWebVR().add(function (event) { if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) { return; } _this._vrDevice = event.vrDisplay; //reset the rig parameters. _this.setCameraRigMode(_Cameras_camera__WEBPACK_IMPORTED_MODULE_3__["Camera"].RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion }); if (_this._attached) { _this.getEngine().enableVR(_this.webVROptions); } }); if (typeof (VRFrameData) !== "undefined") { _this._frameData = new VRFrameData(); } if (webVROptions.useMultiview) { if (!_this.getScene().getEngine().getCaps().multiview) { _Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Warn("Multiview is not supported, falling back to standard rendering"); _this._useMultiviewToSingleView = false; } else { _this._useMultiviewToSingleView = true; _this._rigPostProcess = new _PostProcesses_vrMultiviewToSingleviewPostProcess__WEBPACK_IMPORTED_MODULE_10__["VRMultiviewToSingleviewPostProcess"]("VRMultiviewToSingleview", _this, 1.0); } } /** * The idea behind the following lines: * objects that have the camera as parent should actually have the rig cameras as a parent. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera, * the second will not show it correctly. * * To solve this - each object that has the camera as parent will be added to a protected array. * When the rig camera renders, it will take this array and set all of those to be its children. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly. * Amazing! */ scene.onBeforeCameraRenderObservable.add(function (camera) { if (camera.parent === _this && _this.rigParenting) { _this._descendants = _this.getDescendants(true, function (n) { // don't take the cameras or the controllers! var isController = _this.controllers.some(function (controller) { return controller._mesh === n; }); var isRigCamera = _this._rigCameras.indexOf(n) !== -1; return !isController && !isRigCamera; }); _this._descendants.forEach(function (node) { node.parent = camera; }); } }); scene.onAfterCameraRenderObservable.add(function (camera) { if (camera.parent === _this && _this.rigParenting) { _this._descendants.forEach(function (node) { node.parent = _this; }); } }); return _this; } /** * Gets the device distance from the ground in meters. * @returns the distance in meters from the vrDevice to ground in device space. If standing matrix is not supported for the vrDevice 0 is returned. */ WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () { if (this._standingMatrix) { // Add standing matrix offset to get real offset from ground in room this._standingMatrix.getTranslationToRef(this._workingVector); return this._deviceRoomPosition.y + this._workingVector.y; } //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero. return this._defaultHeight || 0; }; /** * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported. */ WebVRFreeCamera.prototype.useStandingMatrix = function (callback) { var _this = this; if (callback === void 0) { callback = function (bool) { }; } // Use standing matrix if available this.getEngine().initWebVRAsync().then(function (result) { if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) { callback(false); } else { _this._standingMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"](); _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix); if (!_this.getScene().useRightHandedSystem) { if (_this._standingMatrix) { _this._standingMatrix.toggleModelMatrixHandInPlace(); } } callback(true); } }); }; /** * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground. * @returns A promise with a boolean set to if the standing matrix is supported. */ WebVRFreeCamera.prototype.useStandingMatrixAsync = function () { var _this = this; return new Promise(function (res) { _this.useStandingMatrix(function (supported) { res(supported); }); }); }; /** * Disposes the camera */ WebVRFreeCamera.prototype.dispose = function () { this._detachIfAttached(); this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled); if (this._updateCacheWhenTrackingDisabledObserver) { this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver); } _super.prototype.dispose.call(this); }; /** * Gets a vrController by name. * @param name The name of the controller to retreive * @returns the controller matching the name specified or null if not found */ WebVRFreeCamera.prototype.getControllerByName = function (name) { for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) { var gp = _a[_i]; if (gp.hand === name) { return gp; } } return null; }; Object.defineProperty(WebVRFreeCamera.prototype, "leftController", { /** * The controller corresponding to the users left hand. */ get: function () { if (!this._leftController) { this._leftController = this.getControllerByName("left"); } return this._leftController; }, enumerable: false, configurable: true }); Object.defineProperty(WebVRFreeCamera.prototype, "rightController", { /** * The controller corresponding to the users right hand. */ get: function () { if (!this._rightController) { this._rightController = this.getControllerByName("right"); } return this._rightController; }, enumerable: false, configurable: true }); /** * Casts a ray forward from the vrCamera's gaze. * @param length Length of the ray (default: 100) * @returns the ray corresponding to the gaze */ WebVRFreeCamera.prototype.getForwardRay = function (length) { if (length === void 0) { length = 100; } if (this.leftCamera) { // Use left eye to avoid computation to compute center on every call return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera } else { return _super.prototype.getForwardRay.call(this, length); } }; /** * @hidden * Updates the camera based on device's frame data */ WebVRFreeCamera.prototype._checkInputs = function () { if (this._vrDevice && this._vrDevice.isPresenting) { this._vrDevice.getFrameData(this._frameData); this.updateFromDevice(this._frameData.pose); } _super.prototype._checkInputs.call(this); }; /** * Updates the poseControlled values based on the input device pose. * @param poseData Pose coming from the device */ WebVRFreeCamera.prototype.updateFromDevice = function (poseData) { if (poseData && poseData.orientation && poseData.orientation.length === 4) { this.rawPose = poseData; this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]); if (this.getScene().useRightHandedSystem) { this._deviceRoomRotationQuaternion.z *= -1; this._deviceRoomRotationQuaternion.w *= -1; } if (this.webVROptions.trackPosition && this.rawPose.position) { this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]); if (this.getScene().useRightHandedSystem) { this._deviceRoomPosition.z *= -1; } } this._poseSet = true; } }; /** * WebVR's attach control will start broadcasting frames to the device. * Note that in certain browsers (chrome for example) this function must be called * within a user-interaction callback. Example: *
scene.onPointerDown = function() { camera.attachControl(canvas); }
*
* @param element html element to attach the vrDevice to
* @param noPreventDefault prevent the default html element operation when attaching the vrDevice
*/
WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
_super.prototype.attachControl.call(this, element, noPreventDefault);
this._attached = true;
this._htmlElementAttached = element;
noPreventDefault = _Cameras_camera__WEBPACK_IMPORTED_MODULE_3__["Camera"].ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
if (this._vrDevice) {
this.getEngine().enableVR(this.webVROptions);
}
var hostWindow = this._scene.getEngine().getHostWindow();
if (hostWindow) {
hostWindow.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
}
};
/**
* Detaches the camera from the html element and disables VR
*
* @param element html element to detach from
*/
WebVRFreeCamera.prototype.detachControl = function (element) {
this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
_super.prototype.detachControl.call(this, element);
this._attached = false;
this.getEngine().disableVR();
window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
};
/**
* @returns the name of this class
*/
WebVRFreeCamera.prototype.getClassName = function () {
return "WebVRFreeCamera";
};
/**
* Calls resetPose on the vrDisplay
* See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
*/
WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
//uses the vrDisplay's "resetPose()".
//pitch and roll won't be affected.
this._vrDevice.resetPose();
};
/**
* @hidden
* Updates the rig cameras (left and right eye)
*/
WebVRFreeCamera.prototype._updateRigCameras = function () {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
camLeft.position.copyFrom(this._deviceRoomPosition);
camRight.position.copyFrom(this._deviceRoomPosition);
};
// Remove translation from 6dof headset if trackposition is set to false
WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
if (isViewMatrix === void 0) { isViewMatrix = false; }
if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
if (!isViewMatrix) {
this._tmpMatrix.invert();
}
this._tmpMatrix.multiplyToRef(matrix, matrix);
}
};
/**
* @hidden
* Updates the cached values of the camera
* @param ignoreParentClass ignores updating the parent class's cache (default: false)
*/
WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
var _this = this;
if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
// Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
if (!this.updateCacheCalled) {
// make sure it is only called once per loop. this.update() might cause an infinite loop.
this.updateCacheCalled = true;
this.update();
}
// Set working vector to the device position in room space rotated by the new rotation
this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
// Subtract this vector from the current device position in world to get the translation for the device world matrix
this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
// Add translation from anchor position
this._deviceToWorld.getTranslationToRef(this._workingVector);
this._workingVector.addInPlace(this.position);
this._workingVector.subtractInPlace(this._cache.position);
this._deviceToWorld.setTranslation(this._workingVector);
// Set an inverted matrix to be used when updating the camera
this._deviceToWorld.invertToRef(this._worldToDevice);
// Update the gamepad to ensure the mesh is updated on the same frame as camera
this.controllers.forEach(function (controller) {
controller._deviceToWorld.copyFrom(_this._deviceToWorld);
_this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
controller.update();
});
}
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this.updateCacheCalled = false;
};
/**
* @hidden
* Get current device position in babylon world
*/
WebVRFreeCamera.prototype._computeDevicePosition = function () {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
};
/**
* Updates the current device position and rotation in the babylon world
*/
WebVRFreeCamera.prototype.update = function () {
this._computeDevicePosition();
// Get current device rotation in babylon world
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Quaternion"].FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
if (this._poseSet) {
this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
}
_super.prototype.update.call(this);
};
/**
* @hidden
* Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
* @returns an identity matrix
*/
WebVRFreeCamera.prototype._getViewMatrix = function () {
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity();
};
/**
* This function is called by the two RIG cameras.
* 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
* @hidden
*/
WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
// Update the parent camera prior to using a child camera to avoid desynchronization
var parentCamera = this._cameraRigParams["parentCamera"];
parentCamera._updateCache();
//WebVR 1.1
var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
if (!this.getScene().useRightHandedSystem) {
this._webvrViewMatrix.toggleModelMatrixHandInPlace();
}
// update the camera rotation matrix
this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
// Computing target and final matrix
this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
// should the view matrix be updated with scale and position offset?
if (parentCamera.deviceScaleFactor !== 1) {
this._webvrViewMatrix.invert();
// scale the position, if set
if (parentCamera.deviceScaleFactor) {
this._webvrViewMatrix.multiplyAtIndex(12, parentCamera.deviceScaleFactor);
this._webvrViewMatrix.multiplyAtIndex(13, parentCamera.deviceScaleFactor);
this._webvrViewMatrix.multiplyAtIndex(14, parentCamera.deviceScaleFactor);
}
this._webvrViewMatrix.invert();
}
// Remove translation from 6dof headset if trackposition is set to false
parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
// Compute global position
this._workingMatrix = this._workingMatrix || _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Identity();
this._webvrViewMatrix.invertToRef(this._workingMatrix);
this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
this._workingMatrix.getTranslationToRef(this._globalPosition);
this._markSyncedWithParent();
return this._webvrViewMatrix;
};
/** @hidden */
WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
var parentCamera = this.parent;
parentCamera._vrDevice.depthNear = parentCamera.minZ;
parentCamera._vrDevice.depthFar = parentCamera.maxZ;
var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].FromArrayToRef(projectionArray, 0, this._projectionMatrix);
//babylon compatible matrix
if (!this.getScene().useRightHandedSystem) {
this._projectionMatrix.toggleProjectionMatrixHandInPlace();
}
return this._projectionMatrix;
};
/**
* Initializes the controllers and their meshes
*/
WebVRFreeCamera.prototype.initControllers = function () {
var _this = this;
this.controllers = [];
var manager = this.getScene().gamepadManager;
this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED) {
var webVrController = gamepad;
if (webVrController.defaultModel) {
webVrController.defaultModel.setEnabled(false);
}
if (webVrController.hand === "right") {
_this._rightController = null;
}
if (webVrController.hand === "left") {
_this._leftController = null;
}
var controllerIndex = _this.controllers.indexOf(webVrController);
if (controllerIndex !== -1) {
_this.controllers.splice(controllerIndex, 1);
}
}
});
this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
if (gamepad.type === _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED) {
var webVrController_1 = gamepad;
if (!_this.webVROptions.trackPosition) {
webVrController_1._disableTrackPosition(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"](webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
// Cache must be updated before rendering controllers to avoid them being one frame behind
if (!_this._updateCacheWhenTrackingDisabledObserver) {
_this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
_this._updateCache();
});
}
}
webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
_this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
if (_this.webVROptions.controllerMeshes) {
if (webVrController_1.defaultModel) {
webVrController_1.defaultModel.setEnabled(true);
}
else {
// Load the meshes
webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
_this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
if (_this.webVROptions.defaultLightingOnControllers) {
if (!_this._lightOnControllers) {
_this._lightOnControllers = new _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_8__["HemisphericLight"]("vrControllersLight", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"](0, 1, 0), _this.getScene());
}
var activateLightOnSubMeshes_1 = function (mesh, light) {
var children = mesh.getChildren();
if (children && children.length !== 0) {
children.forEach(function (mesh) {
light.includedOnlyMeshes.push(mesh);
activateLightOnSubMeshes_1(mesh, light);
});
}
};
_this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
}
});
}
}
webVrController_1.attachToPoseControlledCamera(_this);
// since this is async - sanity check. Is the controller already stored?
if (_this.controllers.indexOf(webVrController_1) === -1) {
//add to the controllers array
_this.controllers.push(webVrController_1);
// Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
// Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
// So we're overriding setting left & right manually to be sure
var firstViveWandDetected = false;
for (var i = 0; i < _this.controllers.length; i++) {
if (_this.controllers[i].controllerType === _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_6__["PoseEnabledControllerType"].VIVE) {
if (!firstViveWandDetected) {
firstViveWandDetected = true;
_this.controllers[i].hand = "left";
}
else {
_this.controllers[i].hand = "right";
}
}
}
//did we find enough controllers? Great! let the developer know.
if (_this.controllers.length >= 2) {
_this.onControllersAttachedObservable.notifyObservers(_this.controllers);
}
}
}
});
};
return WebVRFreeCamera;
}(_Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_2__["FreeCamera"]));
/***/ }),
/***/ "./Cameras/arcRotateCamera.ts":
/*!************************************!*\
!*** ./Cameras/arcRotateCamera.ts ***!
\************************************/
/*! exports provided: ArcRotateCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return ArcRotateCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Behaviors_Cameras_autoRotationBehavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Behaviors/Cameras/autoRotationBehavior */ "./Behaviors/Cameras/autoRotationBehavior.ts");
/* harmony import */ var _Behaviors_Cameras_bouncingBehavior__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Behaviors/Cameras/bouncingBehavior */ "./Behaviors/Cameras/bouncingBehavior.ts");
/* harmony import */ var _Behaviors_Cameras_framingBehavior__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Behaviors/Cameras/framingBehavior */ "./Behaviors/Cameras/framingBehavior.ts");
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts");
/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts");
/* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts");
/* harmony import */ var _Maths_math_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Maths/math.constants */ "./Maths/math.constants.ts");
_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("ArcRotateCamera", function (name, scene) {
return function () { return new ArcRotateCamera(name, 0, 0, 1.0, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); };
});
/**
* This represents an orbital type of camera.
*
* This camera always points towards a given target position and can be rotated around that target with the target as the centre of rotation. It can be controlled with cursors and mouse, or with touch events.
* Think of this camera as one orbiting its target position, or more imaginatively as a spy satellite orbiting the earth. Its position relative to the target (earth) can be set by three parameters, alpha (radians) the longitudinal rotation, beta (radians) the latitudinal rotation and radius the distance from the target position.
* @see https://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
*/
var ArcRotateCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ArcRotateCamera, _super);
/**
* Instantiates a new ArcRotateCamera in a given scene
* @param name Defines the name of the camera
* @param alpha Defines the camera rotation along the logitudinal axis
* @param beta Defines the camera rotation along the latitudinal axis
* @param radius Defines the camera distance from its target
* @param target Defines the camera target
* @param scene Defines the scene the camera belongs to
* @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
*/
function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
var _this = _super.call(this, name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene, setActiveOnSceneIfNoneActive) || this;
/**
* Current inertia value on the longitudinal axis.
* The bigger this number the longer it will take for the camera to stop.
*/
_this.inertialAlphaOffset = 0;
/**
* Current inertia value on the latitudinal axis.
* The bigger this number the longer it will take for the camera to stop.
*/
_this.inertialBetaOffset = 0;
/**
* Current inertia value on the radius axis.
* The bigger this number the longer it will take for the camera to stop.
*/
_this.inertialRadiusOffset = 0;
/**
* Minimum allowed angle on the longitudinal axis.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.lowerAlphaLimit = null;
/**
* Maximum allowed angle on the longitudinal axis.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.upperAlphaLimit = null;
/**
* Minimum allowed angle on the latitudinal axis.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.lowerBetaLimit = 0.01;
/**
* Maximum allowed angle on the latitudinal axis.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.upperBetaLimit = Math.PI - 0.01;
/**
* Minimum allowed distance of the camera to the target (The camera can not get closer).
* This can help limiting how the Camera is able to move in the scene.
*/
_this.lowerRadiusLimit = null;
/**
* Maximum allowed distance of the camera to the target (The camera can not get further).
* This can help limiting how the Camera is able to move in the scene.
*/
_this.upperRadiusLimit = null;
/**
* Defines the current inertia value used during panning of the camera along the X axis.
*/
_this.inertialPanningX = 0;
/**
* Defines the current inertia value used during panning of the camera along the Y axis.
*/
_this.inertialPanningY = 0;
/**
* Defines the distance used to consider the camera in pan mode vs pinch/zoom.
* Basically if your fingers moves away from more than this distance you will be considered
* in pinch mode.
*/
_this.pinchToPanMaxDistance = 20;
/**
* Defines the maximum distance the camera can pan.
* This could help keeping the cammera always in your scene.
*/
_this.panningDistanceLimit = null;
/**
* Defines the target of the camera before paning.
*/
_this.panningOriginTarget = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
/**
* Defines the value of the inertia used during panning.
* 0 would mean stop inertia and one would mean no decelleration at all.
*/
_this.panningInertia = 0.9;
//-- end properties for backward compatibility for inputs
/**
* Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
*/
_this.zoomOnFactor = 1;
/**
* Defines a screen offset for the camera position.
*/
_this.targetScreenOffset = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero();
/**
* Allows the camera to be completely reversed.
* If false the camera can not arrive upside down.
*/
_this.allowUpsideDown = true;
/**
* Define if double tap/click is used to restore the previously saved state of the camera.
*/
_this.useInputToRestoreState = true;
/** @hidden */
_this._viewMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
/**
* Defines the allowed panning axis.
*/
_this.panningAxis = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 1, 0);
/**
* Observable triggered when the mesh target has been changed on the camera.
*/
_this.onMeshTargetChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Defines whether the camera should check collision with the objects oh the scene.
* @see https://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
*/
_this.checkCollisions = false;
/**
* Defines the collision radius of the camera.
* This simulates a sphere around the camera.
* @see https://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
*/
_this.collisionRadius = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0.5, 0.5, 0.5);
_this._previousPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
_this._collisionVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
_this._newPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
_this._computationVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
_this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) { collidedMesh = null; }
if (!collidedMesh) {
_this._previousPosition.copyFrom(_this._position);
}
else {
_this.setPosition(newPosition);
if (_this.onCollide) {
_this.onCollide(collidedMesh);
}
}
// Recompute because of constraints
var cosa = Math.cos(_this.alpha);
var sina = Math.sin(_this.alpha);
var cosb = Math.cos(_this.beta);
var sinb = Math.sin(_this.beta);
if (sinb === 0) {
sinb = 0.0001;
}
var target = _this._getTargetPosition();
_this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
target.addToRef(_this._computationVector, _this._newPosition);
_this._position.copyFrom(_this._newPosition);
var up = _this.upVector;
if (_this.allowUpsideDown && _this.beta < 0) {
up = up.clone();
up = up.negate();
}
_this._computeViewMatrix(_this._position, target, up);
_this._viewMatrix.addAtIndex(12, _this.targetScreenOffset.x);
_this._viewMatrix.addAtIndex(13, _this.targetScreenOffset.y);
_this._collisionTriggered = false;
};
_this._target = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
if (target) {
_this.setTarget(target);
}
_this.alpha = alpha;
_this.beta = beta;
_this.radius = radius;
_this.getViewMatrix();
_this.inputs = new _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__["ArcRotateCameraInputsManager"](_this);
_this.inputs.addKeyboard().addMouseWheel().addPointers();
return _this;
}
Object.defineProperty(ArcRotateCamera.prototype, "target", {
/**
* Defines the target point of the camera.
* The camera looks towards it form the radius distance.
* Please note that you can set the target to a mesh and thus the target will be copied from mesh.position
*/
get: function () {
return this._target;
},
set: function (value) {
this.setTarget(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "position", {
/**
* Define the current local position of the camera in the scene
*/
get: function () {
return this._position;
},
set: function (newPosition) {
this.setPosition(newPosition);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "upVector", {
get: function () {
return this._upVector;
},
/**
* The vector the camera should consider as up. (default is Vector3(0, 1, 0) as returned by Vector3.Up())
* Setting this will copy the given vector to the camera's upVector, and set rotation matrices to and from Y up.
* DO NOT set the up vector using copyFrom or copyFromFloats, as this bypasses setting the above matrices.
*/
set: function (vec) {
if (!this._upToYMatrix) {
this._YToUpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
this._upToYMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
this._upVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
}
vec.normalize();
this._upVector.copyFrom(vec);
this.setMatUp();
},
enumerable: false,
configurable: true
});
/**
* Sets the Y-up to camera up-vector rotation matrix, and the up-vector to Y-up rotation matrix.
*/
ArcRotateCamera.prototype.setMatUp = function () {
// from y-up to custom-up (used in _getViewMatrix)
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAlignToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._upVector, this._YToUpMatrix);
// from custom-up to y-up (used in rebuildAnglesAndRadius)
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAlignToRef(this._upVector, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].UpReadOnly, this._upToYMatrix);
};
Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
//-- begin properties for backward compatibility for inputs
/**
* Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
*/
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.angularSensibilityX;
}
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.angularSensibilityX = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
/**
* Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
*/
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.angularSensibilityY;
}
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.angularSensibilityY = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
/**
* Gets or Set the pointer pinch precision or how fast is the camera zooming.
*/
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.pinchPrecision;
}
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.pinchPrecision = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
/**
* Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
* It will be used instead of pinchDeltaPrecision if different from 0.
* It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
*/
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.pinchDeltaPercentage;
}
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.pinchDeltaPercentage = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useNaturalPinchZoom", {
/**
* Gets or Set the pointer use natural pinch zoom to override the pinch precision
* and pinch delta percentage.
* When useNaturalPinchZoom is true, multi touch zoom will zoom in such
* that any object in the plane at the camera's target point will scale
* perfectly with finger motion.
*/
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.useNaturalPinchZoom;
}
return false;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.useNaturalPinchZoom = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
/**
* Gets or Set the pointer panning sensibility or how fast is the camera moving.
*/
get: function () {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
return pointers.panningSensibility;
}
return 0;
},
set: function (value) {
var pointers = this.inputs.attached["pointers"];
if (pointers) {
pointers.panningSensibility = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
/**
* Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysUp;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysUp = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
/**
* Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysDown;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysDown = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
/**
* Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysLeft;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysLeft = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
/**
* Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysRight;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysRight = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
/**
* Gets or Set the mouse wheel precision or how fast is the camera zooming.
*/
get: function () {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
return mousewheel.wheelPrecision;
}
return 0;
},
set: function (value) {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
mousewheel.wheelPrecision = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
/**
* Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
* It will be used instead of pinchDeltaPrecision if different from 0.
* It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
*/
get: function () {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
return mousewheel.wheelDeltaPercentage;
}
return 0;
},
set: function (value) {
var mousewheel = this.inputs.attached["mousewheel"];
if (mousewheel) {
mousewheel.wheelDeltaPercentage = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
/**
* Gets the bouncing behavior of the camera if it has been enabled.
* @see https://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
*/
get: function () {
return this._bouncingBehavior;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
/**
* Defines if the bouncing behavior of the camera is enabled on the camera.
* @see https://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
*/
get: function () {
return this._bouncingBehavior != null;
},
set: function (value) {
if (value === this.useBouncingBehavior) {
return;
}
if (value) {
this._bouncingBehavior = new _Behaviors_Cameras_bouncingBehavior__WEBPACK_IMPORTED_MODULE_7__["BouncingBehavior"]();
this.addBehavior(this._bouncingBehavior);
}
else if (this._bouncingBehavior) {
this.removeBehavior(this._bouncingBehavior);
this._bouncingBehavior = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
/**
* Gets the framing behavior of the camera if it has been enabled.
* @see https://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
*/
get: function () {
return this._framingBehavior;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
/**
* Defines if the framing behavior of the camera is enabled on the camera.
* @see https://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
*/
get: function () {
return this._framingBehavior != null;
},
set: function (value) {
if (value === this.useFramingBehavior) {
return;
}
if (value) {
this._framingBehavior = new _Behaviors_Cameras_framingBehavior__WEBPACK_IMPORTED_MODULE_8__["FramingBehavior"]();
this.addBehavior(this._framingBehavior);
}
else if (this._framingBehavior) {
this.removeBehavior(this._framingBehavior);
this._framingBehavior = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
/**
* Gets the auto rotation behavior of the camera if it has been enabled.
* @see https://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
*/
get: function () {
return this._autoRotationBehavior;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
/**
* Defines if the auto rotation behavior of the camera is enabled on the camera.
* @see https://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
*/
get: function () {
return this._autoRotationBehavior != null;
},
set: function (value) {
if (value === this.useAutoRotationBehavior) {
return;
}
if (value) {
this._autoRotationBehavior = new _Behaviors_Cameras_autoRotationBehavior__WEBPACK_IMPORTED_MODULE_6__["AutoRotationBehavior"]();
this.addBehavior(this._autoRotationBehavior);
}
else if (this._autoRotationBehavior) {
this.removeBehavior(this._autoRotationBehavior);
this._autoRotationBehavior = null;
}
},
enumerable: false,
configurable: true
});
// Cache
/** @hidden */
ArcRotateCamera.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache._target = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.alpha = undefined;
this._cache.beta = undefined;
this._cache.radius = undefined;
this._cache.targetScreenOffset = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"].Zero();
};
/** @hidden */
ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this._cache._target.copyFrom(this._getTargetPosition());
this._cache.alpha = this.alpha;
this._cache.beta = this.beta;
this._cache.radius = this.radius;
this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
};
ArcRotateCamera.prototype._getTargetPosition = function () {
if (this._targetHost && this._targetHost.getAbsolutePosition) {
var pos = this._targetHost.absolutePosition;
if (this._targetBoundingCenter) {
pos.addToRef(this._targetBoundingCenter, this._target);
}
else {
this._target.copyFrom(pos);
}
}
var lockedTargetPosition = this._getLockedTargetPosition();
if (lockedTargetPosition) {
return lockedTargetPosition;
}
return this._target;
};
/**
* Stores the current state of the camera (alpha, beta, radius and target)
* @returns the camera itself
*/
ArcRotateCamera.prototype.storeState = function () {
this._storedAlpha = this.alpha;
this._storedBeta = this.beta;
this._storedRadius = this.radius;
this._storedTarget = this._getTargetPosition().clone();
this._storedTargetScreenOffset = this.targetScreenOffset.clone();
return _super.prototype.storeState.call(this);
};
/**
* @hidden
* Restored camera state. You must call storeState() first
*/
ArcRotateCamera.prototype._restoreStateValues = function () {
if (!_super.prototype._restoreStateValues.call(this)) {
return false;
}
this.setTarget(this._storedTarget.clone());
this.alpha = this._storedAlpha;
this.beta = this._storedBeta;
this.radius = this._storedRadius;
this.targetScreenOffset = this._storedTargetScreenOffset.clone();
this.inertialAlphaOffset = 0;
this.inertialBetaOffset = 0;
this.inertialRadiusOffset = 0;
this.inertialPanningX = 0;
this.inertialPanningY = 0;
return true;
};
// Synchronized
/** @hidden */
ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
return false;
}
return this._cache._target.equals(this._getTargetPosition())
&& this._cache.alpha === this.alpha
&& this._cache.beta === this.beta
&& this._cache.radius === this.radius
&& this._cache.targetScreenOffset.equals(this.targetScreenOffset);
};
/**
* Attached controls to the current camera.
* @param element Defines the element the controls should be listened from
* @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
* @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
* @param panningMouseButton Defines whether panning is allowed through mouse click button
*/
ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
var _this = this;
if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
if (panningMouseButton === void 0) { panningMouseButton = 2; }
this._useCtrlForPanning = useCtrlForPanning;
this._panningMouseButton = panningMouseButton;
this.inputs.attachElement(element, noPreventDefault);
this._reset = function () {
_this.inertialAlphaOffset = 0;
_this.inertialBetaOffset = 0;
_this.inertialRadiusOffset = 0;
_this.inertialPanningX = 0;
_this.inertialPanningY = 0;
};
};
/**
* Detach the current controls from the camera.
* The camera will stop reacting to inputs.
* @param element Defines the element to stop listening the inputs from
*/
ArcRotateCamera.prototype.detachControl = function (element) {
this.inputs.detachElement(element);
if (this._reset) {
this._reset();
}
};
/** @hidden */
ArcRotateCamera.prototype._checkInputs = function () {
//if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
if (this._collisionTriggered) {
return;
}
this.inputs.checkInputs();
// Inertia
if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
var inertialAlphaOffset = this.inertialAlphaOffset;
if (this.beta <= 0) {
inertialAlphaOffset *= -1;
}
if (this.getScene().useRightHandedSystem) {
inertialAlphaOffset *= -1;
}
if (this.parent && this.parent._getWorldMatrixDeterminant() < 0) {
inertialAlphaOffset *= -1;
}
this.alpha += inertialAlphaOffset;
this.beta += this.inertialBetaOffset;
this.radius -= this.inertialRadiusOffset;
this.inertialAlphaOffset *= this.inertia;
this.inertialBetaOffset *= this.inertia;
this.inertialRadiusOffset *= this.inertia;
if (Math.abs(this.inertialAlphaOffset) < _Maths_math_constants__WEBPACK_IMPORTED_MODULE_12__["Epsilon"]) {
this.inertialAlphaOffset = 0;
}
if (Math.abs(this.inertialBetaOffset) < _Maths_math_constants__WEBPACK_IMPORTED_MODULE_12__["Epsilon"]) {
this.inertialBetaOffset = 0;
}
if (Math.abs(this.inertialRadiusOffset) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_12__["Epsilon"]) {
this.inertialRadiusOffset = 0;
}
}
// Panning inertia
if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
if (!this._localDirection) {
this._localDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
this._transformedDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
}
this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
this._localDirection.multiplyInPlace(this.panningAxis);
this._viewMatrix.invertToRef(this._cameraTransformMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
//Eliminate y if map panning is enabled (panningAxis == 1,0,1)
if (!this.panningAxis.y) {
this._transformedDirection.y = 0;
}
if (!this._targetHost) {
if (this.panningDistanceLimit) {
this._transformedDirection.addInPlace(this._target);
var distanceSquared = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].DistanceSquared(this._transformedDirection, this.panningOriginTarget);
if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
this._target.copyFrom(this._transformedDirection);
}
}
else {
this._target.addInPlace(this._transformedDirection);
}
}
this.inertialPanningX *= this.panningInertia;
this.inertialPanningY *= this.panningInertia;
if (Math.abs(this.inertialPanningX) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_12__["Epsilon"]) {
this.inertialPanningX = 0;
}
if (Math.abs(this.inertialPanningY) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_12__["Epsilon"]) {
this.inertialPanningY = 0;
}
}
// Limits
this._checkLimits();
_super.prototype._checkInputs.call(this);
};
ArcRotateCamera.prototype._checkLimits = function () {
if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
if (this.allowUpsideDown && this.beta > Math.PI) {
this.beta = this.beta - (2 * Math.PI);
}
}
else {
if (this.beta < this.lowerBetaLimit) {
this.beta = this.lowerBetaLimit;
}
}
if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
if (this.allowUpsideDown && this.beta < -Math.PI) {
this.beta = this.beta + (2 * Math.PI);
}
}
else {
if (this.beta > this.upperBetaLimit) {
this.beta = this.upperBetaLimit;
}
}
if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
this.alpha = this.lowerAlphaLimit;
}
if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
this.alpha = this.upperAlphaLimit;
}
if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
this.radius = this.lowerRadiusLimit;
this.inertialRadiusOffset = 0;
}
if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
this.radius = this.upperRadiusLimit;
this.inertialRadiusOffset = 0;
}
};
/**
* Rebuilds angles (alpha, beta) and radius from the give position and target
*/
ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
this._position.subtractToRef(this._getTargetPosition(), this._computationVector);
// need to rotate to Y up equivalent if up vector not Axis.Y
if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._computationVector, this._upToYMatrix, this._computationVector);
}
this.radius = this._computationVector.length();
if (this.radius === 0) {
this.radius = 0.0001; // Just to avoid division by zero
}
// Alpha
if (this._computationVector.x === 0 && this._computationVector.z === 0) {
this.alpha = Math.PI / 2; // avoid division by zero when looking along up axis, and set to acos(0)
}
else {
this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
}
if (this._computationVector.z < 0) {
this.alpha = 2 * Math.PI - this.alpha;
}
// Beta
this.beta = Math.acos(this._computationVector.y / this.radius);
this._checkLimits();
};
/**
* Use a position to define the current camera related information like alpha, beta and radius
* @param position Defines the position to set the camera at
*/
ArcRotateCamera.prototype.setPosition = function (position) {
if (this._position.equals(position)) {
return;
}
this._position.copyFrom(position);
this.rebuildAnglesAndRadius();
};
/**
* Defines the target the camera should look at.
* This will automatically adapt alpha beta and radius to fit within the new target.
* @param target Defines the new target as a Vector or a mesh
* @param toBoundingCenter In case of a mesh target, defines whether to target the mesh position or its bounding information center
* @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
*/
ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
if (toBoundingCenter === void 0) { toBoundingCenter = false; }
if (allowSamePosition === void 0) { allowSamePosition = false; }
if (target.getBoundingInfo) {
if (toBoundingCenter) {
this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
}
else {
this._targetBoundingCenter = null;
}
target.computeWorldMatrix();
this._targetHost = target;
this._target = this._getTargetPosition();
this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
}
else {
var newTarget = target;
var currentTarget = this._getTargetPosition();
if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
return;
}
this._targetHost = null;
this._target = newTarget;
this._targetBoundingCenter = null;
this.onMeshTargetChangedObservable.notifyObservers(null);
}
this.rebuildAnglesAndRadius();
};
/** @hidden */
ArcRotateCamera.prototype._getViewMatrix = function () {
// Compute
var cosa = Math.cos(this.alpha);
var sina = Math.sin(this.alpha);
var cosb = Math.cos(this.beta);
var sinb = Math.sin(this.beta);
if (sinb === 0) {
sinb = 0.0001;
}
if (this.radius === 0) {
this.radius = 0.0001; // Just to avoid division by zero
}
var target = this._getTargetPosition();
this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
// Rotate according to up vector
if (this._upVector.x !== 0 || this._upVector.y !== 1.0 || this._upVector.z !== 0) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._computationVector, this._YToUpMatrix, this._computationVector);
}
target.addToRef(this._computationVector, this._newPosition);
if (this.getScene().collisionsEnabled && this.checkCollisions) {
var coordinator = this.getScene().collisionCoordinator;
if (!this._collider) {
this._collider = coordinator.createCollider();
}
this._collider._radius = this.collisionRadius;
this._newPosition.subtractToRef(this._position, this._collisionVelocity);
this._collisionTriggered = true;
coordinator.getNewPosition(this._position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
}
else {
this._position.copyFrom(this._newPosition);
var up = this.upVector;
if (this.allowUpsideDown && sinb < 0) {
up = up.negate();
}
this._computeViewMatrix(this._position, target, up);
this._viewMatrix.addAtIndex(12, this.targetScreenOffset.x);
this._viewMatrix.addAtIndex(13, this.targetScreenOffset.y);
}
this._currentTarget = target;
return this._viewMatrix;
};
/**
* Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
* @param meshes Defines the mesh to zoom on
* @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
*/
ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
meshes = meshes || this.getScene().meshes;
var minMaxVector = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].MinMax(meshes);
var distance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Distance(minMaxVector.min, minMaxVector.max);
this.radius = distance * this.zoomOnFactor;
this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
};
/**
* Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
* The target will be changed but the radius
* @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
* @param doNotUpdateMaxZ Defines whether or not maxZ should be updated whilst zooming on the mesh (this can happen if the mesh is big and the maxradius pretty small for instance)
*/
ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
var meshesOrMinMaxVector;
var distance;
if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
meshesOrMinMaxVector = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].MinMax(meshes);
distance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
}
else { //minMaxVector and distance
var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
meshesOrMinMaxVector = minMaxVectorAndDistance;
distance = minMaxVectorAndDistance.distance;
}
this._target = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].Center(meshesOrMinMaxVector);
if (!doNotUpdateMaxZ) {
this.maxZ = distance * 2;
}
};
/**
* @override
* Override Camera.createRigCamera
*/
ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
var alphaShift = 0;
switch (this.cameraRigMode) {
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_INTERLACED:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_VR:
alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
break;
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
break;
}
var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
rigCam._cameraRigParams = {};
rigCam.isRigCamera = true;
rigCam.rigParent = this;
rigCam.upVector = this.upVector;
return rigCam;
};
/**
* @hidden
* @override
* Override Camera._updateRigCameras
*/
ArcRotateCamera.prototype._updateRigCameras = function () {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
camLeft.beta = camRight.beta = this.beta;
switch (this.cameraRigMode) {
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_INTERLACED:
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_VR:
camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
break;
case _camera__WEBPACK_IMPORTED_MODULE_9__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
break;
}
_super.prototype._updateRigCameras.call(this);
};
/**
* Destroy the camera and release the current resources hold by it.
*/
ArcRotateCamera.prototype.dispose = function () {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
/**
* Gets the current object class name.
* @return the class name
*/
ArcRotateCamera.prototype.getClassName = function () {
return "ArcRotateCamera";
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "alpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "beta", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "radius", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("target")
], ArcRotateCamera.prototype, "_target", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "inertialPanningX", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "inertialPanningY", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "panningInertia", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
return ArcRotateCamera;
}(_targetCamera__WEBPACK_IMPORTED_MODULE_10__["TargetCamera"]));
/***/ }),
/***/ "./Cameras/arcRotateCameraInputsManager.ts":
/*!*************************************************!*\
!*** ./Cameras/arcRotateCameraInputsManager.ts ***!
\*************************************************/
/*! exports provided: ArcRotateCameraInputsManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return ArcRotateCameraInputsManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Cameras_Inputs_arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraPointersInput */ "./Cameras/Inputs/arcRotateCameraPointersInput.ts");
/* harmony import */ var _Cameras_Inputs_arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraKeyboardMoveInput */ "./Cameras/Inputs/arcRotateCameraKeyboardMoveInput.ts");
/* harmony import */ var _Cameras_Inputs_arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraMouseWheelInput */ "./Cameras/Inputs/arcRotateCameraMouseWheelInput.ts");
/* harmony import */ var _Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/cameraInputsManager */ "./Cameras/cameraInputsManager.ts");
/**
* Default Inputs manager for the ArcRotateCamera.
* It groups all the default supported inputs for ease of use.
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
*/
var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ArcRotateCameraInputsManager, _super);
/**
* Instantiates a new ArcRotateCameraInputsManager.
* @param camera Defines the camera the inputs belong to
*/
function ArcRotateCameraInputsManager(camera) {
return _super.call(this, camera) || this;
}
/**
* Add mouse wheel input support to the input manager.
* @returns the current input manager
*/
ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
this.add(new _Cameras_Inputs_arcRotateCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__["ArcRotateCameraMouseWheelInput"]());
return this;
};
/**
* Add pointers input support to the input manager.
* @returns the current input manager
*/
ArcRotateCameraInputsManager.prototype.addPointers = function () {
this.add(new _Cameras_Inputs_arcRotateCameraPointersInput__WEBPACK_IMPORTED_MODULE_1__["ArcRotateCameraPointersInput"]());
return this;
};
/**
* Add keyboard input support to the input manager.
* @returns the current input manager
*/
ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
this.add(new _Cameras_Inputs_arcRotateCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCameraKeyboardMoveInput"]());
return this;
};
return ArcRotateCameraInputsManager;
}(_Cameras_cameraInputsManager__WEBPACK_IMPORTED_MODULE_4__["CameraInputsManager"]));
/***/ }),
/***/ "./Cameras/camera.ts":
/*!***************************!*\
!*** ./Cameras/camera.ts ***!
\***************************/
/*! exports provided: Camera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return Camera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/smartArray */ "./Misc/smartArray.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Maths/math.viewport */ "./Maths/math.viewport.ts");
/* harmony import */ var _Maths_math_frustum__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Maths/math.frustum */ "./Maths/math.frustum.ts");
/**
* This is the base class of all the camera used in the application.
* @see https://doc.babylonjs.com/features/cameras
*/
var Camera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Camera, _super);
/**
* Instantiates a new camera object.
* This should not be used directly but through the inherited cameras: ArcRotate, Free...
* @see https://doc.babylonjs.com/features/cameras
* @param name Defines the name of the camera in the scene
* @param position Defines the position of the camera
* @param scene Defines the scene the camera belongs too
* @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
*/
function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
var _this = _super.call(this, name, scene) || this;
/** @hidden */
_this._position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero();
_this._upVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Up();
/**
* Define the current limit on the left side for an orthographic camera
* In scene unit
*/
_this.orthoLeft = null;
/**
* Define the current limit on the right side for an orthographic camera
* In scene unit
*/
_this.orthoRight = null;
/**
* Define the current limit on the bottom side for an orthographic camera
* In scene unit
*/
_this.orthoBottom = null;
/**
* Define the current limit on the top side for an orthographic camera
* In scene unit
*/
_this.orthoTop = null;
/**
* Field Of View is set in Radians. (default is 0.8)
*/
_this.fov = 0.8;
/**
* Define the minimum distance the camera can see from.
* This is important to note that the depth buffer are not infinite and the closer it starts
* the more your scene might encounter depth fighting issue.
*/
_this.minZ = 1;
/**
* Define the maximum distance the camera can see to.
* This is important to note that the depth buffer are not infinite and the further it end
* the more your scene might encounter depth fighting issue.
*/
_this.maxZ = 10000.0;
/**
* Define the default inertia of the camera.
* This helps giving a smooth feeling to the camera movement.
*/
_this.inertia = 0.9;
/**
* Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.ORTHOGRAPHIC_CAMERA)
*/
_this.mode = Camera.PERSPECTIVE_CAMERA;
/**
* Define whether the camera is intermediate.
* This is useful to not present the output directly to the screen in case of rig without post process for instance
*/
_this.isIntermediate = false;
/**
* Define the viewport of the camera.
* This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
*/
_this.viewport = new _Maths_math_viewport__WEBPACK_IMPORTED_MODULE_10__["Viewport"](0, 0, 1.0, 1.0);
/**
* Restricts the camera to viewing objects with the same layerMask.
* A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
*/
_this.layerMask = 0x0FFFFFFF;
/**
* fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
*/
_this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
/**
* Rig mode of the camera.
* This is useful to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
* This is normally controlled byt the camera themselves as internal use.
*/
_this.cameraRigMode = Camera.RIG_MODE_NONE;
/**
* Defines the list of custom render target which are rendered to and then used as the input to this camera's render. Eg. display another camera view on a TV in the main scene
* This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
* else in the scene. (Eg. security camera)
*
* To change the final output target of the camera, camera.outputRenderTarget should be used instead (eg. webXR renders to a render target corrisponding to an HMD)
*/
_this.customRenderTargets = new Array();
/**
* When set, the camera will render to this render target instead of the default canvas
*
* If the desire is to use the output of a camera as a texture in the scene consider using camera.customRenderTargets instead
*/
_this.outputRenderTarget = null;
/**
* Observable triggered when the camera view matrix has changed.
*/
_this.onViewMatrixChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"]();
/**
* Observable triggered when the camera Projection matrix has changed.
*/
_this.onProjectionMatrixChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"]();
/**
* Observable triggered when the inputs have been processed.
*/
_this.onAfterCheckInputsObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"]();
/**
* Observable triggered when reset has been called and applied to the camera.
*/
_this.onRestoreStateObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_4__["Observable"]();
/**
* Is this camera a part of a rig system?
*/
_this.isRigCamera = false;
/** @hidden */
_this._rigCameras = new Array();
_this._webvrViewMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity();
/** @hidden */
_this._skipRendering = false;
/** @hidden */
_this._projectionMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"]();
/** @hidden */
_this._postProcesses = new Array();
/** @hidden */
_this._activeMeshes = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__["SmartArray"](256);
_this._globalPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero();
/** @hidden */
_this._computedViewMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity();
_this._doNotComputeProjectionMatrix = false;
_this._transformMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Zero();
_this._refreshFrustumPlanes = true;
/** @hidden */
_this._isCamera = true;
/** @hidden */
_this._isLeftCamera = false;
/** @hidden */
_this._isRightCamera = false;
_this.getScene().addCamera(_this);
if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
_this.getScene().activeCamera = _this;
}
_this.position = position;
return _this;
}
Object.defineProperty(Camera.prototype, "position", {
/**
* Define the current local position of the camera in the scene
*/
get: function () {
return this._position;
},
set: function (newPosition) {
this._position = newPosition;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "upVector", {
get: function () {
return this._upVector;
},
/**
* The vector the camera should consider as up.
* (default is Vector3(0, 1, 0) aka Vector3.Up())
*/
set: function (vec) {
this._upVector = vec;
},
enumerable: false,
configurable: true
});
/**
* Store current camera state (fov, position, etc..)
* @returns the camera
*/
Camera.prototype.storeState = function () {
this._stateStored = true;
this._storedFov = this.fov;
return this;
};
/**
* Restores the camera state values if it has been stored. You must call storeState() first
*/
Camera.prototype._restoreStateValues = function () {
if (!this._stateStored) {
return false;
}
this.fov = this._storedFov;
return true;
};
/**
* Restored camera state. You must call storeState() first.
* @returns true if restored and false otherwise
*/
Camera.prototype.restoreState = function () {
if (this._restoreStateValues()) {
this.onRestoreStateObservable.notifyObservers(this);
return true;
}
return false;
};
/**
* Gets the class name of the camera.
* @returns the class name
*/
Camera.prototype.getClassName = function () {
return "Camera";
};
/**
* Gets a string representation of the camera useful for debug purpose.
* @param fullDetails Defines that a more verboe level of logging is required
* @returns the string representation
*/
Camera.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + this.getClassName();
if (this.animations) {
for (var i = 0; i < this.animations.length; i++) {
ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
}
}
if (fullDetails) {
}
return ret;
};
Object.defineProperty(Camera.prototype, "globalPosition", {
/**
* Gets the current world space position of the camera.
*/
get: function () {
return this._globalPosition;
},
enumerable: false,
configurable: true
});
/**
* Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
* @returns the active meshe list
*/
Camera.prototype.getActiveMeshes = function () {
return this._activeMeshes;
};
/**
* Check whether a mesh is part of the current active mesh list of the camera
* @param mesh Defines the mesh to check
* @returns true if active, false otherwise
*/
Camera.prototype.isActiveMesh = function (mesh) {
return (this._activeMeshes.indexOf(mesh) !== -1);
};
/**
* Is this camera ready to be used/rendered
* @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
* @return true if the camera is ready
*/
Camera.prototype.isReady = function (completeCheck) {
if (completeCheck === void 0) { completeCheck = false; }
if (completeCheck) {
for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
var pp = _a[_i];
if (pp && !pp.isReady()) {
return false;
}
}
}
return _super.prototype.isReady.call(this, completeCheck);
};
/** @hidden */
Camera.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache.position = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.upVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.mode = undefined;
this._cache.minZ = undefined;
this._cache.maxZ = undefined;
this._cache.fov = undefined;
this._cache.fovMode = undefined;
this._cache.aspectRatio = undefined;
this._cache.orthoLeft = undefined;
this._cache.orthoRight = undefined;
this._cache.orthoBottom = undefined;
this._cache.orthoTop = undefined;
this._cache.renderWidth = undefined;
this._cache.renderHeight = undefined;
};
/** @hidden */
Camera.prototype._updateCache = function (ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
this._cache.position.copyFrom(this.position);
this._cache.upVector.copyFrom(this.upVector);
};
/** @hidden */
Camera.prototype._isSynchronized = function () {
return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
};
/** @hidden */
Camera.prototype._isSynchronizedViewMatrix = function () {
if (!_super.prototype._isSynchronized.call(this)) {
return false;
}
return this._cache.position.equals(this.position)
&& this._cache.upVector.equals(this.upVector)
&& this.isSynchronizedWithParent();
};
/** @hidden */
Camera.prototype._isSynchronizedProjectionMatrix = function () {
var check = this._cache.mode === this.mode
&& this._cache.minZ === this.minZ
&& this._cache.maxZ === this.maxZ;
if (!check) {
return false;
}
var engine = this.getEngine();
if (this.mode === Camera.PERSPECTIVE_CAMERA) {
check = this._cache.fov === this.fov
&& this._cache.fovMode === this.fovMode
&& this._cache.aspectRatio === engine.getAspectRatio(this);
}
else {
check = this._cache.orthoLeft === this.orthoLeft
&& this._cache.orthoRight === this.orthoRight
&& this._cache.orthoBottom === this.orthoBottom
&& this._cache.orthoTop === this.orthoTop
&& this._cache.renderWidth === engine.getRenderWidth()
&& this._cache.renderHeight === engine.getRenderHeight();
}
return check;
};
/**
* Attach the input controls to a specific dom element to get the input from.
* @param element Defines the element the controls should be listened from
* @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
*/
Camera.prototype.attachControl = function (element, noPreventDefault) {
};
/**
* Detach the current controls from the specified dom element.
* @param element Defines the element to stop listening the inputs from
*/
Camera.prototype.detachControl = function (element) {
};
/**
* Update the camera state according to the different inputs gathered during the frame.
*/
Camera.prototype.update = function () {
this._checkInputs();
if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
this._updateRigCameras();
}
};
/** @hidden */
Camera.prototype._checkInputs = function () {
this.onAfterCheckInputsObservable.notifyObservers(this);
};
Object.defineProperty(Camera.prototype, "rigCameras", {
/** @hidden */
get: function () {
return this._rigCameras;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "rigPostProcess", {
/**
* Gets the post process used by the rig cameras
*/
get: function () {
return this._rigPostProcess;
},
enumerable: false,
configurable: true
});
/**
* Internal, gets the first post proces.
* @returns the first post process to be run on this camera.
*/
Camera.prototype._getFirstPostProcess = function () {
for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
if (this._postProcesses[ppIndex] !== null) {
return this._postProcesses[ppIndex];
}
}
return null;
};
Camera.prototype._cascadePostProcessesToRigCams = function () {
// invalidate framebuffer
var firstPostProcess = this._getFirstPostProcess();
if (firstPostProcess) {
firstPostProcess.markTextureDirty();
}
// glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
for (var i = 0, len = this._rigCameras.length; i < len; i++) {
var cam = this._rigCameras[i];
var rigPostProcess = cam._rigPostProcess;
// for VR rig, there does not have to be a post process
if (rigPostProcess) {
var isPass = rigPostProcess.getEffectName() === "pass";
if (isPass) {
// any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
cam.isIntermediate = this._postProcesses.length === 0;
}
cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
rigPostProcess.markTextureDirty();
}
else {
cam._postProcesses = this._postProcesses.slice(0);
}
}
};
/**
* Attach a post process to the camera.
* @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
* @param postProcess The post process to attach to the camera
* @param insertAt The position of the post process in case several of them are in use in the scene
* @returns the position the post process has been inserted at
*/
Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
if (insertAt === void 0) { insertAt = null; }
if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_7__["Logger"].Error("You're trying to reuse a post process not defined as reusable.");
return 0;
}
if (insertAt == null || insertAt < 0) {
this._postProcesses.push(postProcess);
}
else if (this._postProcesses[insertAt] === null) {
this._postProcesses[insertAt] = postProcess;
}
else {
this._postProcesses.splice(insertAt, 0, postProcess);
}
this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
return this._postProcesses.indexOf(postProcess);
};
/**
* Detach a post process to the camera.
* @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
* @param postProcess The post process to detach from the camera
*/
Camera.prototype.detachPostProcess = function (postProcess) {
var idx = this._postProcesses.indexOf(postProcess);
if (idx !== -1) {
this._postProcesses[idx] = null;
}
this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
};
/**
* Gets the current world matrix of the camera
*/
Camera.prototype.getWorldMatrix = function () {
if (this._isSynchronizedViewMatrix()) {
return this._worldMatrix;
}
// Getting the the view matrix will also compute the world matrix.
this.getViewMatrix();
return this._worldMatrix;
};
/** @hidden */
Camera.prototype._getViewMatrix = function () {
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity();
};
/**
* Gets the current view matrix of the camera.
* @param force forces the camera to recompute the matrix without looking at the cached state
* @returns the view matrix
*/
Camera.prototype.getViewMatrix = function (force) {
if (!force && this._isSynchronizedViewMatrix()) {
return this._computedViewMatrix;
}
this.updateCache();
this._computedViewMatrix = this._getViewMatrix();
this._currentRenderId = this.getScene().getRenderId();
this._childUpdateId++;
this._refreshFrustumPlanes = true;
if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
}
// Notify parent camera if rig camera is changed
if (this.parent && this.parent.onViewMatrixChangedObservable) {
this.parent.onViewMatrixChangedObservable.notifyObservers(this.parent);
}
this.onViewMatrixChangedObservable.notifyObservers(this);
this._computedViewMatrix.invertToRef(this._worldMatrix);
return this._computedViewMatrix;
};
/**
* Freeze the projection matrix.
* It will prevent the cache check of the camera projection compute and can speed up perf
* if no parameter of the camera are meant to change
* @param projection Defines manually a projection if necessary
*/
Camera.prototype.freezeProjectionMatrix = function (projection) {
this._doNotComputeProjectionMatrix = true;
if (projection !== undefined) {
this._projectionMatrix = projection;
}
};
/**
* Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
*/
Camera.prototype.unfreezeProjectionMatrix = function () {
this._doNotComputeProjectionMatrix = false;
};
/**
* Gets the current projection matrix of the camera.
* @param force forces the camera to recompute the matrix without looking at the cached state
* @returns the projection matrix
*/
Camera.prototype.getProjectionMatrix = function (force) {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
return this._projectionMatrix;
}
// Cache
this._cache.mode = this.mode;
this._cache.minZ = this.minZ;
this._cache.maxZ = this.maxZ;
// Matrix
this._refreshFrustumPlanes = true;
var engine = this.getEngine();
var scene = this.getScene();
if (this.mode === Camera.PERSPECTIVE_CAMERA) {
this._cache.fov = this.fov;
this._cache.fovMode = this.fovMode;
this._cache.aspectRatio = engine.getAspectRatio(this);
if (this.minZ <= 0) {
this.minZ = 0.1;
}
var reverseDepth = engine.useReverseDepthBuffer;
var getProjectionMatrix = void 0;
if (scene.useRightHandedSystem) {
getProjectionMatrix = reverseDepth ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovReverseRHToRef : _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovRHToRef;
}
else {
getProjectionMatrix = reverseDepth ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovReverseLHToRef : _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovLHToRef;
}
getProjectionMatrix(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
}
else {
var halfWidth = engine.getRenderWidth() / 2.0;
var halfHeight = engine.getRenderHeight() / 2.0;
if (scene.useRightHandedSystem) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].OrthoOffCenterRHToRef((_a = this.orthoLeft) !== null && _a !== void 0 ? _a : -halfWidth, (_b = this.orthoRight) !== null && _b !== void 0 ? _b : halfWidth, (_c = this.orthoBottom) !== null && _c !== void 0 ? _c : -halfHeight, (_d = this.orthoTop) !== null && _d !== void 0 ? _d : halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
}
else {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].OrthoOffCenterLHToRef((_e = this.orthoLeft) !== null && _e !== void 0 ? _e : -halfWidth, (_f = this.orthoRight) !== null && _f !== void 0 ? _f : halfWidth, (_g = this.orthoBottom) !== null && _g !== void 0 ? _g : -halfHeight, (_h = this.orthoTop) !== null && _h !== void 0 ? _h : halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
}
this._cache.orthoLeft = this.orthoLeft;
this._cache.orthoRight = this.orthoRight;
this._cache.orthoBottom = this.orthoBottom;
this._cache.orthoTop = this.orthoTop;
this._cache.renderWidth = engine.getRenderWidth();
this._cache.renderHeight = engine.getRenderHeight();
}
this.onProjectionMatrixChangedObservable.notifyObservers(this);
return this._projectionMatrix;
};
/**
* Gets the transformation matrix (ie. the multiplication of view by projection matrices)
* @returns a Matrix
*/
Camera.prototype.getTransformationMatrix = function () {
this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
return this._transformMatrix;
};
Camera.prototype._updateFrustumPlanes = function () {
if (!this._refreshFrustumPlanes) {
return;
}
this.getTransformationMatrix();
if (!this._frustumPlanes) {
this._frustumPlanes = _Maths_math_frustum__WEBPACK_IMPORTED_MODULE_11__["Frustum"].GetPlanes(this._transformMatrix);
}
else {
_Maths_math_frustum__WEBPACK_IMPORTED_MODULE_11__["Frustum"].GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
}
this._refreshFrustumPlanes = false;
};
/**
* Checks if a cullable object (mesh...) is in the camera frustum
* This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
* @param target The object to check
* @param checkRigCameras If the rig cameras should be checked (eg. with webVR camera both eyes should be checked) (Default: false)
* @returns true if the object is in frustum otherwise false
*/
Camera.prototype.isInFrustum = function (target, checkRigCameras) {
if (checkRigCameras === void 0) { checkRigCameras = false; }
this._updateFrustumPlanes();
if (checkRigCameras && this.rigCameras.length > 0) {
var result = false;
this.rigCameras.forEach(function (cam) {
cam._updateFrustumPlanes();
result = result || target.isInFrustum(cam._frustumPlanes);
});
return result;
}
else {
return target.isInFrustum(this._frustumPlanes);
}
};
/**
* Checks if a cullable object (mesh...) is in the camera frustum
* Unlike isInFrustum this cheks the full bounding box
* @param target The object to check
* @returns true if the object is in frustum otherwise false
*/
Camera.prototype.isCompletelyInFrustum = function (target) {
this._updateFrustumPlanes();
return target.isCompletelyInFrustum(this._frustumPlanes);
};
/**
* Gets a ray in the forward direction from the camera.
* @param length Defines the length of the ray to create
* @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
* @param origin Defines the start point of the ray which defaults to the camera position
* @returns the forward ray
*/
Camera.prototype.getForwardRay = function (length, transform, origin) {
if (length === void 0) { length = 100; }
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("Ray");
};
/**
* Gets a ray in the forward direction from the camera.
* @param refRay the ray to (re)use when setting the values
* @param length Defines the length of the ray to create
* @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
* @param origin Defines the start point of the ray which defaults to the camera position
* @returns the forward ray
*/
Camera.prototype.getForwardRayToRef = function (refRay, length, transform, origin) {
if (length === void 0) { length = 100; }
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("Ray");
};
/**
* Releases resources associated with this node.
* @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
* @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
*/
Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
// Observables
this.onViewMatrixChangedObservable.clear();
this.onProjectionMatrixChangedObservable.clear();
this.onAfterCheckInputsObservable.clear();
this.onRestoreStateObservable.clear();
// Inputs
if (this.inputs) {
this.inputs.clear();
}
// Animations
this.getScene().stopAnimation(this);
// Remove from scene
this.getScene().removeCamera(this);
while (this._rigCameras.length > 0) {
var camera = this._rigCameras.pop();
if (camera) {
camera.dispose();
}
}
// Postprocesses
if (this._rigPostProcess) {
this._rigPostProcess.dispose(this);
this._rigPostProcess = null;
this._postProcesses = [];
}
else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
this._rigPostProcess = null;
this._postProcesses = [];
}
else {
var i = this._postProcesses.length;
while (--i >= 0) {
var postProcess = this._postProcesses[i];
if (postProcess) {
postProcess.dispose(this);
}
}
}
// Render targets
var i = this.customRenderTargets.length;
while (--i >= 0) {
this.customRenderTargets[i].dispose();
}
this.customRenderTargets = [];
// Active Meshes
this._activeMeshes.dispose();
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
Object.defineProperty(Camera.prototype, "isLeftCamera", {
/**
* Gets the left camera of a rig setup in case of Rigged Camera
*/
get: function () {
return this._isLeftCamera;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "isRightCamera", {
/**
* Gets the right camera of a rig setup in case of Rigged Camera
*/
get: function () {
return this._isRightCamera;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "leftCamera", {
/**
* Gets the left camera of a rig setup in case of Rigged Camera
*/
get: function () {
if (this._rigCameras.length < 1) {
return null;
}
return this._rigCameras[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(Camera.prototype, "rightCamera", {
/**
* Gets the right camera of a rig setup in case of Rigged Camera
*/
get: function () {
if (this._rigCameras.length < 2) {
return null;
}
return this._rigCameras[1];
},
enumerable: false,
configurable: true
});
/**
* Gets the left camera target of a rig setup in case of Rigged Camera
* @returns the target position
*/
Camera.prototype.getLeftTarget = function () {
if (this._rigCameras.length < 1) {
return null;
}
return this._rigCameras[0].getTarget();
};
/**
* Gets the right camera target of a rig setup in case of Rigged Camera
* @returns the target position
*/
Camera.prototype.getRightTarget = function () {
if (this._rigCameras.length < 2) {
return null;
}
return this._rigCameras[1].getTarget();
};
/**
* @hidden
*/
Camera.prototype.setCameraRigMode = function (mode, rigParams) {
if (this.cameraRigMode === mode) {
return;
}
while (this._rigCameras.length > 0) {
var camera = this._rigCameras.pop();
if (camera) {
camera.dispose();
}
}
this.cameraRigMode = mode;
this._cameraRigParams = {};
//we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
//not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
this._cameraRigParams.stereoHalfAngle = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
// create the rig cameras, unless none
if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
var leftCamera = this.createRigCamera(this.name + "_L", 0);
if (leftCamera) {
leftCamera._isLeftCamera = true;
}
var rightCamera = this.createRigCamera(this.name + "_R", 1);
if (rightCamera) {
rightCamera._isRightCamera = true;
}
if (leftCamera && rightCamera) {
this._rigCameras.push(leftCamera);
this._rigCameras.push(rightCamera);
}
}
switch (this.cameraRigMode) {
case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
Camera._setStereoscopicAnaglyphRigMode(this);
break;
case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
case Camera.RIG_MODE_STEREOSCOPIC_INTERLACED:
Camera._setStereoscopicRigMode(this);
break;
case Camera.RIG_MODE_VR:
Camera._setVRRigMode(this, rigParams);
break;
case Camera.RIG_MODE_WEBVR:
Camera._setWebVRRigMode(this, rigParams);
break;
}
this._cascadePostProcessesToRigCams();
this.update();
};
/** @hidden */
Camera._setStereoscopicRigMode = function (camera) {
throw "Import Cameras/RigModes/stereoscopicRigMode before using stereoscopic rig mode";
};
/** @hidden */
Camera._setStereoscopicAnaglyphRigMode = function (camera) {
throw "Import Cameras/RigModes/stereoscopicAnaglyphRigMode before using stereoscopic anaglyph rig mode";
};
/** @hidden */
Camera._setVRRigMode = function (camera, rigParams) {
throw "Import Cameras/RigModes/vrRigMode before using VR rig mode";
};
/** @hidden */
Camera._setWebVRRigMode = function (camera, rigParams) {
throw "Import Cameras/RigModes/WebVRRigMode before using Web VR rig mode";
};
/** @hidden */
Camera.prototype._getVRProjectionMatrix = function () {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
return this._projectionMatrix;
};
Camera.prototype._updateCameraRotationMatrix = function () {
//Here for WebVR
};
Camera.prototype._updateWebVRCameraRotationMatrix = function () {
//Here for WebVR
};
/**
* This function MUST be overwritten by the different WebVR cameras available.
* The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
* @hidden
*/
Camera.prototype._getWebVRProjectionMatrix = function () {
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity();
};
/**
* This function MUST be overwritten by the different WebVR cameras available.
* The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
* @hidden
*/
Camera.prototype._getWebVRViewMatrix = function () {
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity();
};
/** @hidden */
Camera.prototype.setCameraRigParameter = function (name, value) {
if (!this._cameraRigParams) {
this._cameraRigParams = {};
}
this._cameraRigParams[name] = value;
//provisionnally:
if (name === "interaxialDistance") {
this._cameraRigParams.stereoHalfAngle = _Misc_tools__WEBPACK_IMPORTED_MODULE_3__["Tools"].ToRadians(value / 0.0637);
}
};
/**
* needs to be overridden by children so sub has required properties to be copied
* @hidden
*/
Camera.prototype.createRigCamera = function (name, cameraIndex) {
return null;
};
/**
* May need to be overridden by children
* @hidden
*/
Camera.prototype._updateRigCameras = function () {
for (var i = 0; i < this._rigCameras.length; i++) {
this._rigCameras[i].minZ = this.minZ;
this._rigCameras[i].maxZ = this.maxZ;
this._rigCameras[i].fov = this.fov;
this._rigCameras[i].upVector.copyFrom(this.upVector);
}
// only update viewport when ANAGLYPH
if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
}
};
/** @hidden */
Camera.prototype._setupInputs = function () {
};
/**
* Serialiaze the camera setup to a json represention
* @returns the JSON representation
*/
Camera.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
// Type
serializationObject.type = this.getClassName();
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
if (this.inputs) {
this.inputs.serialize(serializationObject);
}
// Animations
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
return serializationObject;
};
/**
* Clones the current camera.
* @param name The cloned camera name
* @returns the cloned camera
*/
Camera.prototype.clone = function (name) {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
};
/**
* Gets the direction of the camera relative to a given local axis.
* @param localAxis Defines the reference axis to provide a relative direction.
* @return the direction
*/
Camera.prototype.getDirection = function (localAxis) {
var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero();
this.getDirectionToRef(localAxis, result);
return result;
};
Object.defineProperty(Camera.prototype, "absoluteRotation", {
/**
* Returns the current camera absolute rotation
*/
get: function () {
var result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Quaternion"].Zero();
this.getWorldMatrix().decompose(undefined, result);
return result;
},
enumerable: false,
configurable: true
});
/**
* Gets the direction of the camera relative to a given local axis into a passed vector.
* @param localAxis Defines the reference axis to provide a relative direction.
* @param result Defines the vector to store the result in
*/
Camera.prototype.getDirectionToRef = function (localAxis, result) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
};
/**
* Gets a camera constructor for a given camera type
* @param type The type of the camera to construct (should be equal to one of the camera class name)
* @param name The name of the camera the result will be able to instantiate
* @param scene The scene the result will construct the camera in
* @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
* @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
* @returns a factory method to construc the camera
*/
Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
if (interaxial_distance === void 0) { interaxial_distance = 0; }
if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
var constructorFunc = _node__WEBPACK_IMPORTED_MODULE_6__["Node"].Construct(type, name, scene, {
interaxial_distance: interaxial_distance,
isStereoscopicSideBySide: isStereoscopicSideBySide
});
if (constructorFunc) {
return constructorFunc;
}
// Default to universal camera
return function () { return Camera._createDefaultParsedCamera(name, scene); };
};
/**
* Compute the world matrix of the camera.
* @returns the camera world matrix
*/
Camera.prototype.computeWorldMatrix = function () {
return this.getWorldMatrix();
};
/**
* Parse a JSON and creates the camera from the parsed information
* @param parsedCamera The JSON to parse
* @param scene The scene to instantiate the camera in
* @returns the newly constructed camera
*/
Camera.Parse = function (parsedCamera, scene) {
var type = parsedCamera.type;
var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
var camera = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(construct, parsedCamera, scene);
// Parent
if (parsedCamera.parentId) {
camera._waitingParentId = parsedCamera.parentId;
}
//If camera has an input manager, let it parse inputs settings
if (camera.inputs) {
camera.inputs.parse(parsedCamera);
camera._setupInputs();
}
if (camera.setPosition) { // need to force position
camera.position.copyFromFloats(0, 0, 0);
camera.setPosition(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].FromArray(parsedCamera.position));
}
// Target
if (parsedCamera.target) {
if (camera.setTarget) {
camera.setTarget(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].FromArray(parsedCamera.target));
}
}
// Apply 3d rig, when found
if (parsedCamera.cameraRigMode) {
var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
}
// Animations
if (parsedCamera.animations) {
for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
var parsedAnimation = parsedCamera.animations[animationIndex];
var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].GetClass("BABYLON.Animation");
if (internalClass) {
camera.animations.push(internalClass.Parse(parsedAnimation));
}
}
_node__WEBPACK_IMPORTED_MODULE_6__["Node"].ParseAnimationRanges(camera, parsedCamera, scene);
}
if (parsedCamera.autoAnimate) {
scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
}
return camera;
};
/** @hidden */
Camera._createDefaultParsedCamera = function (name, scene) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("UniversalCamera");
};
/**
* This is the default projection mode used by the cameras.
* It helps recreating a feeling of perspective and better appreciate depth.
* This is the best way to simulate real life cameras.
*/
Camera.PERSPECTIVE_CAMERA = 0;
/**
* This helps creating camera with an orthographic mode.
* Orthographic is commonly used in engineering as a means to produce object specifications that communicate dimensions unambiguously, each line of 1 unit length (cm, meter..whatever) will appear to have the same length everywhere on the drawing. This allows the drafter to dimension only a subset of lines and let the reader know that other lines of that length on the drawing are also that length in reality. Every parallel line in the drawing is also parallel in the object.
*/
Camera.ORTHOGRAPHIC_CAMERA = 1;
/**
* This is the default FOV mode for perspective cameras.
* This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
*/
Camera.FOVMODE_VERTICAL_FIXED = 0;
/**
* This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
*/
Camera.FOVMODE_HORIZONTAL_FIXED = 1;
/**
* This specifies ther is no need for a camera rig.
* Basically only one eye is rendered corresponding to the camera.
*/
Camera.RIG_MODE_NONE = 0;
/**
* Simulates a camera Rig with one blue eye and one red eye.
* This can be use with 3d blue and red glasses.
*/
Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
/**
* Defines that both eyes of the camera will be rendered side by side with a parallel target.
*/
Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
/**
* Defines that both eyes of the camera will be rendered side by side with a none parallel target.
*/
Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
/**
* Defines that both eyes of the camera will be rendered over under each other.
*/
Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
/**
* Defines that both eyes of the camera will be rendered on successive lines interlaced for passive 3d monitors.
*/
Camera.RIG_MODE_STEREOSCOPIC_INTERLACED = 14;
/**
* Defines that both eyes of the camera should be renderered in a VR mode (carbox).
*/
Camera.RIG_MODE_VR = 20;
/**
* Defines that both eyes of the camera should be renderered in a VR mode (webVR).
*/
Camera.RIG_MODE_WEBVR = 21;
/**
* Custom rig mode allowing rig cameras to be populated manually with any number of cameras
*/
Camera.RIG_MODE_CUSTOM = 22;
/**
* Defines if by default attaching controls should prevent the default javascript event to continue.
*/
Camera.ForceAttachControlToAlwaysPreventDefault = false;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("position")
], Camera.prototype, "_position", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])("upVector")
], Camera.prototype, "_upVector", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "orthoLeft", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "orthoRight", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "orthoBottom", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "orthoTop", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "fov", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "minZ", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "maxZ", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "inertia", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "mode", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "layerMask", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "fovMode", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "cameraRigMode", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "interaxialDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Camera.prototype, "isStereoscopicSideBySide", void 0);
return Camera;
}(_node__WEBPACK_IMPORTED_MODULE_6__["Node"]));
/***/ }),
/***/ "./Cameras/cameraInputsManager.ts":
/*!****************************************!*\
!*** ./Cameras/cameraInputsManager.ts ***!
\****************************************/
/*! exports provided: CameraInputTypes, CameraInputsManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return CameraInputTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return CameraInputsManager; });
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts");
/**
* @ignore
* This is a list of all the different input types that are available in the application.
* Fo instance: ArcRotateCameraGamepadInput...
*/
var CameraInputTypes = {};
/**
* This represents the input manager used within a camera.
* It helps dealing with all the different kind of input attached to a camera.
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
*/
var CameraInputsManager = /** @class */ (function () {
/**
* Instantiate a new Camera Input Manager.
* @param camera Defines the camera the input manager blongs to
*/
function CameraInputsManager(camera) {
this.attached = {};
this.camera = camera;
this.checkInputs = function () { };
}
/**
* Add an input method to a camera
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
* @param input camera input method
*/
CameraInputsManager.prototype.add = function (input) {
var type = input.getSimpleName();
if (this.attached[type]) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("camera input of type " + type + " already exists on camera");
return;
}
this.attached[type] = input;
input.camera = this.camera;
//for checkInputs, we are dynamically creating a function
//the goal is to avoid the performance penalty of looping for inputs in the render loop
if (input.checkInputs) {
this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
}
if (this.attachedElement) {
input.attachControl(this.attachedElement);
}
};
/**
* Remove a specific input method from a camera
* example: camera.inputs.remove(camera.inputs.attached.mouse);
* @param inputToRemove camera input method
*/
CameraInputsManager.prototype.remove = function (inputToRemove) {
for (var cam in this.attached) {
var input = this.attached[cam];
if (input === inputToRemove) {
input.detachControl(this.attachedElement);
input.camera = null;
delete this.attached[cam];
this.rebuildInputCheck();
}
}
};
/**
* Remove a specific input type from a camera
* example: camera.inputs.remove("ArcRotateCameraGamepadInput");
* @param inputType the type of the input to remove
*/
CameraInputsManager.prototype.removeByType = function (inputType) {
for (var cam in this.attached) {
var input = this.attached[cam];
if (input.getClassName() === inputType) {
input.detachControl(this.attachedElement);
input.camera = null;
delete this.attached[cam];
this.rebuildInputCheck();
}
}
};
CameraInputsManager.prototype._addCheckInputs = function (fn) {
var current = this.checkInputs;
return function () {
current();
fn();
};
};
/**
* Attach the input controls to the currently attached dom element to listen the events from.
* @param input Defines the input to attach
*/
CameraInputsManager.prototype.attachInput = function (input) {
if (this.attachedElement) {
input.attachControl(this.attachedElement, this.noPreventDefault);
}
};
/**
* Attach the current manager inputs controls to a specific dom element to listen the events from.
* @param element Defines the dom element to collect the events from
* @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
*/
CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
if (noPreventDefault === void 0) { noPreventDefault = false; }
if (this.attachedElement) {
return;
}
noPreventDefault = _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
this.attachedElement = element;
this.noPreventDefault = noPreventDefault;
for (var cam in this.attached) {
this.attached[cam].attachControl(element, noPreventDefault);
}
};
/**
* Detach the current manager inputs controls from a specific dom element.
* @param element Defines the dom element to collect the events from
* @param disconnect Defines whether the input should be removed from the current list of attached inputs
*/
CameraInputsManager.prototype.detachElement = function (element, disconnect) {
if (disconnect === void 0) { disconnect = false; }
if (this.attachedElement !== element) {
return;
}
for (var cam in this.attached) {
this.attached[cam].detachControl(element);
if (disconnect) {
this.attached[cam].camera = null;
}
}
this.attachedElement = null;
};
/**
* Rebuild the dynamic inputCheck function from the current list of
* defined inputs in the manager.
*/
CameraInputsManager.prototype.rebuildInputCheck = function () {
this.checkInputs = function () { };
for (var cam in this.attached) {
var input = this.attached[cam];
if (input.checkInputs) {
this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
}
}
};
/**
* Remove all attached input methods from a camera
*/
CameraInputsManager.prototype.clear = function () {
if (this.attachedElement) {
this.detachElement(this.attachedElement, true);
}
this.attached = {};
this.attachedElement = null;
this.checkInputs = function () { };
};
/**
* Serialize the current input manager attached to a camera.
* This ensures than once parsed,
* the input associated to the camera will be identical to the current ones
* @param serializedCamera Defines the camera serialization JSON the input serialization should write to
*/
CameraInputsManager.prototype.serialize = function (serializedCamera) {
var inputs = {};
for (var cam in this.attached) {
var input = this.attached[cam];
var res = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(input);
inputs[input.getClassName()] = res;
}
serializedCamera.inputsmgr = inputs;
};
/**
* Parses an input manager serialized JSON to restore the previous list of inputs
* and states associated to a camera.
* @param parsedCamera Defines the JSON to parse
*/
CameraInputsManager.prototype.parse = function (parsedCamera) {
var parsedInputs = parsedCamera.inputsmgr;
if (parsedInputs) {
this.clear();
for (var n in parsedInputs) {
var construct = CameraInputTypes[n];
if (construct) {
var parsedinput = parsedInputs[n];
var input = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new construct(); }, parsedinput, null);
this.add(input);
}
}
}
else {
//2016-03-08 this part is for managing backward compatibility
for (var n in this.attached) {
var construct = CameraInputTypes[this.attached[n].getClassName()];
if (construct) {
var input = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new construct(); }, parsedCamera, null);
this.remove(this.attached[n]);
this.add(input);
}
}
}
};
return CameraInputsManager;
}());
/***/ }),
/***/ "./Cameras/deviceOrientationCamera.ts":
/*!********************************************!*\
!*** ./Cameras/deviceOrientationCamera.ts ***!
\********************************************/
/*! exports provided: DeviceOrientationCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return DeviceOrientationCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _Inputs_freeCameraDeviceOrientationInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/freeCameraDeviceOrientationInput */ "./Cameras/Inputs/freeCameraDeviceOrientationInput.ts");
/* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
return function () { return new DeviceOrientationCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
// We're mainly based on the logic defined into the FreeCamera code
/**
* This is a camera specifically designed to react to device orientation events such as a modern mobile device
* being tilted forward or back and left or right.
*/
var DeviceOrientationCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DeviceOrientationCamera, _super);
/**
* Creates a new device orientation camera
* @param name The name of the camera
* @param position The start position camera
* @param scene The scene the camera belongs to
*/
function DeviceOrientationCamera(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this._tmpDragQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
_this._disablePointerInputWhenUsingDeviceOrientation = true;
_this._dragFactor = 0;
_this._quaternionCache = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
_this.inputs.addDeviceOrientation();
// When the orientation sensor fires it's first event, disable mouse input
if (_this.inputs._deviceOrientationInput) {
_this.inputs._deviceOrientationInput._onDeviceOrientationChangedObservable.addOnce(function () {
if (_this._disablePointerInputWhenUsingDeviceOrientation) {
if (_this.inputs._mouseInput) {
_this.inputs._mouseInput._allowCameraRotation = false;
_this.inputs._mouseInput.onPointerMovedObservable.add(function (e) {
if (_this._dragFactor != 0) {
if (!_this._initialQuaternion) {
_this._initialQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
}
// Rotate the initial space around the y axis to allow users to "turn around" via touch/mouse
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].FromEulerAnglesToRef(0, e.offsetX * _this._dragFactor, 0, _this._tmpDragQuaternion);
_this._initialQuaternion.multiplyToRef(_this._tmpDragQuaternion, _this._initialQuaternion);
}
});
}
}
});
}
return _this;
}
Object.defineProperty(DeviceOrientationCamera.prototype, "disablePointerInputWhenUsingDeviceOrientation", {
/**
* Gets or sets a boolean indicating that pointer input must be disabled on first orientation sensor update (Default: true)
*/
get: function () {
return this._disablePointerInputWhenUsingDeviceOrientation;
},
set: function (value) {
this._disablePointerInputWhenUsingDeviceOrientation = value;
},
enumerable: false,
configurable: true
});
/**
* Enabled turning on the y axis when the orientation sensor is active
* @param dragFactor the factor that controls the turn speed (default: 1/300)
*/
DeviceOrientationCamera.prototype.enableHorizontalDragging = function (dragFactor) {
if (dragFactor === void 0) { dragFactor = 1 / 300; }
this._dragFactor = dragFactor;
};
/**
* Gets the current instance class name ("DeviceOrientationCamera").
* This helps avoiding instanceof at run time.
* @returns the class name
*/
DeviceOrientationCamera.prototype.getClassName = function () {
return "DeviceOrientationCamera";
};
/**
* @hidden
* Checks and applies the current values of the inputs to the camera. (Internal use only)
*/
DeviceOrientationCamera.prototype._checkInputs = function () {
_super.prototype._checkInputs.call(this);
this._quaternionCache.copyFrom(this.rotationQuaternion);
if (this._initialQuaternion) {
this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
}
};
/**
* Reset the camera to its default orientation on the specified axis only.
* @param axis The axis to reset
*/
DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
var _this = this;
if (axis === void 0) { axis = _Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].Y; }
//can only work if this camera has a rotation quaternion already.
if (!this.rotationQuaternion) {
return;
}
if (!this._initialQuaternion) {
this._initialQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
}
this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
['x', 'y', 'z'].forEach(function (axisName) {
if (!axis[axisName]) {
_this._initialQuaternion[axisName] = 0;
}
else {
_this._initialQuaternion[axisName] *= -1;
}
});
this._initialQuaternion.normalize();
//force rotation update
this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
};
return DeviceOrientationCamera;
}(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"]));
/***/ }),
/***/ "./Cameras/flyCamera.ts":
/*!******************************!*\
!*** ./Cameras/flyCamera.ts ***!
\******************************/
/*! exports provided: FlyCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return FlyCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts");
/* harmony import */ var _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./flyCameraInputsManager */ "./Cameras/flyCameraInputsManager.ts");
/**
* This is a flying camera, designed for 3D movement and rotation in all directions,
* such as in a 3D Space Shooter or a Flight Simulator.
*/
var FlyCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FlyCamera, _super);
/**
* Instantiates a FlyCamera.
* This is a flying camera, designed for 3D movement and rotation in all directions,
* such as in a 3D Space Shooter or a Flight Simulator.
* @param name Define the name of the camera in the scene.
* @param position Define the starting position of the camera in the scene.
* @param scene Define the scene the camera belongs to.
* @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active, if no other camera has been defined as active.
*/
function FlyCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
/**
* Define the collision ellipsoid of the camera.
* This is helpful for simulating a camera body, like a player's body.
* @see https://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
*/
_this.ellipsoid = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 1, 1);
/**
* Define an offset for the position of the ellipsoid around the camera.
* This can be helpful if the camera is attached away from the player's body center,
* such as at its head.
*/
_this.ellipsoidOffset = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0);
/**
* Enable or disable collisions of the camera with the rest of the scene objects.
*/
_this.checkCollisions = false;
/**
* Enable or disable gravity on the camera.
*/
_this.applyGravity = false;
/**
* Define the current direction the camera is moving to.
*/
_this.cameraDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
/**
* Track Roll to maintain the wanted Rolling when looking around.
*/
_this._trackRoll = 0;
/**
* Slowly correct the Roll to its original value after a Pitch+Yaw rotation.
*/
_this.rollCorrect = 100;
/**
* Mimic a banked turn, Rolling the camera when Yawing.
* It's recommended to use rollCorrect = 10 for faster banking correction.
*/
_this.bankedTurn = false;
/**
* Limit in radians for how much Roll banking will add. (Default: 90°)
*/
_this.bankedTurnLimit = Math.PI / 2;
/**
* Value of 0 disables the banked Roll.
* Value of 1 is equal to the Yaw angle in radians.
*/
_this.bankedTurnMultiplier = 1;
_this._needMoveForGravity = false;
_this._oldPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._diffPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._newPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
// Collisions.
_this._collisionMask = -1;
/** @hidden */
_this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) { collidedMesh = null; }
var updatePosition = function (newPos) {
_this._newPosition.copyFrom(newPos);
_this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
if (_this._diffPosition.length() > _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].CollisionsEpsilon) {
_this.position.addInPlace(_this._diffPosition);
if (_this.onCollide && collidedMesh) {
_this.onCollide(collidedMesh);
}
}
};
updatePosition(newPosition);
};
_this.inputs = new _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FlyCameraInputsManager"](_this);
_this.inputs.addKeyboard().addMouse();
return _this;
}
Object.defineProperty(FlyCamera.prototype, "angularSensibility", {
/**
* Gets the input sensibility for mouse input.
* Higher values reduce sensitivity.
*/
get: function () {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
return mouse.angularSensibility;
}
return 0;
},
/**
* Sets the input sensibility for a mouse input.
* Higher values reduce sensitivity.
*/
set: function (value) {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
mouse.angularSensibility = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlyCamera.prototype, "keysForward", {
/**
* Get the keys for camera movement forward.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysForward;
}
return [];
},
/**
* Set the keys for camera movement forward.
*/
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysForward = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlyCamera.prototype, "keysBackward", {
/**
* Get the keys for camera movement backward.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysBackward;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysBackward = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlyCamera.prototype, "keysUp", {
/**
* Get the keys for camera movement up.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysUp;
}
return [];
},
/**
* Set the keys for camera movement up.
*/
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysUp = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlyCamera.prototype, "keysDown", {
/**
* Get the keys for camera movement down.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysDown;
}
return [];
},
/**
* Set the keys for camera movement down.
*/
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysDown = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlyCamera.prototype, "keysLeft", {
/**
* Get the keys for camera movement left.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysLeft;
}
return [];
},
/**
* Set the keys for camera movement left.
*/
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysLeft = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FlyCamera.prototype, "keysRight", {
/**
* Set the keys for camera movement right.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysRight;
}
return [];
},
/**
* Set the keys for camera movement right.
*/
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysRight = value;
}
},
enumerable: false,
configurable: true
});
/**
* Attach a control to the HTML DOM element.
* @param element Defines the element that listens to the input events.
* @param noPreventDefault Defines whether events caught by the controls should call preventdefault(). https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
*/
FlyCamera.prototype.attachControl = function (element, noPreventDefault) {
this.inputs.attachElement(element, noPreventDefault);
};
/**
* Detach a control from the HTML DOM element.
* The camera will stop reacting to that input.
* @param element Defines the element that listens to the input events.
*/
FlyCamera.prototype.detachControl = function (element) {
this.inputs.detachElement(element);
this.cameraDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0);
};
Object.defineProperty(FlyCamera.prototype, "collisionMask", {
/**
* Get the mask that the camera ignores in collision events.
*/
get: function () {
return this._collisionMask;
},
/**
* Set the mask that the camera ignores in collision events.
*/
set: function (mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: false,
configurable: true
});
/** @hidden */
FlyCamera.prototype._collideWithWorld = function (displacement) {
var globalPosition;
if (this.parent) {
globalPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this.position, this.parent.getWorldMatrix());
}
else {
globalPosition = this.position;
}
globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
this._oldPosition.addInPlace(this.ellipsoidOffset);
var coordinator = this.getScene().collisionCoordinator;
if (!this._collider) {
this._collider = coordinator.createCollider();
}
this._collider._radius = this.ellipsoid;
this._collider.collisionMask = this._collisionMask;
// No need for clone, as long as gravity is not on.
var actualDisplacement = displacement;
// Add gravity to direction to prevent dual-collision checking.
if (this.applyGravity) {
// This prevents mending with cameraDirection, a global variable of the fly camera class.
actualDisplacement = displacement.add(this.getScene().gravity);
}
coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
};
/** @hidden */
FlyCamera.prototype._checkInputs = function () {
if (!this._localDirection) {
this._localDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
this._transformedDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
}
this.inputs.checkInputs();
_super.prototype._checkInputs.call(this);
};
/** @hidden */
FlyCamera.prototype._decideIfNeedsToMove = function () {
return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
/** @hidden */
FlyCamera.prototype._updatePosition = function () {
if (this.checkCollisions && this.getScene().collisionsEnabled) {
this._collideWithWorld(this.cameraDirection);
}
else {
_super.prototype._updatePosition.call(this);
}
};
/**
* Restore the Roll to its target value at the rate specified.
* @param rate - Higher means slower restoring.
* @hidden
*/
FlyCamera.prototype.restoreRoll = function (rate) {
var limit = this._trackRoll; // Target Roll.
var z = this.rotation.z; // Current Roll.
var delta = limit - z; // Difference in Roll.
var minRad = 0.001; // Tenth of a radian is a barely noticable difference.
// If the difference is noticable, restore the Roll.
if (Math.abs(delta) >= minRad) {
// Change Z rotation towards the target Roll.
this.rotation.z += delta / rate;
// Match when near enough.
if (Math.abs(limit - this.rotation.z) <= minRad) {
this.rotation.z = limit;
}
}
};
/**
* Destroy the camera and release the current resources held by it.
*/
FlyCamera.prototype.dispose = function () {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
/**
* Get the current object class name.
* @returns the class name.
*/
FlyCamera.prototype.getClassName = function () {
return "FlyCamera";
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], FlyCamera.prototype, "ellipsoid", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], FlyCamera.prototype, "ellipsoidOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FlyCamera.prototype, "checkCollisions", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FlyCamera.prototype, "applyGravity", void 0);
return FlyCamera;
}(_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"]));
/***/ }),
/***/ "./Cameras/flyCameraInputsManager.ts":
/*!*******************************************!*\
!*** ./Cameras/flyCameraInputsManager.ts ***!
\*******************************************/
/*! exports provided: FlyCameraInputsManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return FlyCameraInputsManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts");
/* harmony import */ var _Cameras_Inputs_flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/flyCameraMouseInput */ "./Cameras/Inputs/flyCameraMouseInput.ts");
/* harmony import */ var _Cameras_Inputs_flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/flyCameraKeyboardInput */ "./Cameras/Inputs/flyCameraKeyboardInput.ts");
/**
* Default Inputs manager for the FlyCamera.
* It groups all the default supported inputs for ease of use.
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
*/
var FlyCameraInputsManager = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FlyCameraInputsManager, _super);
/**
* Instantiates a new FlyCameraInputsManager.
* @param camera Defines the camera the inputs belong to.
*/
function FlyCameraInputsManager(camera) {
return _super.call(this, camera) || this;
}
/**
* Add keyboard input support to the input manager.
* @returns the new FlyCameraKeyboardMoveInput().
*/
FlyCameraInputsManager.prototype.addKeyboard = function () {
this.add(new _Cameras_Inputs_flyCameraKeyboardInput__WEBPACK_IMPORTED_MODULE_3__["FlyCameraKeyboardInput"]());
return this;
};
/**
* Add mouse input support to the input manager.
* @param touchEnabled Enable touch screen support.
* @returns the new FlyCameraMouseInput().
*/
FlyCameraInputsManager.prototype.addMouse = function (touchEnabled) {
if (touchEnabled === void 0) { touchEnabled = true; }
this.add(new _Cameras_Inputs_flyCameraMouseInput__WEBPACK_IMPORTED_MODULE_2__["FlyCameraMouseInput"](touchEnabled));
return this;
};
return FlyCameraInputsManager;
}(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"]));
/***/ }),
/***/ "./Cameras/followCamera.ts":
/*!*********************************!*\
!*** ./Cameras/followCamera.ts ***!
\*********************************/
/*! exports provided: FollowCamera, ArcFollowCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return FollowCamera; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return ArcFollowCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./followCameraInputsManager */ "./Cameras/followCameraInputsManager.ts");
_node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("FollowCamera", function (name, scene) {
return function () { return new FollowCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene); };
});
_node__WEBPACK_IMPORTED_MODULE_5__["Node"].AddNodeConstructor("ArcFollowCamera", function (name, scene) {
return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
});
/**
* A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
* an arc rotate version arcFollowCamera are available.
* @see https://doc.babylonjs.com/features/cameras#follow-camera
*/
var FollowCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FollowCamera, _super);
/**
* Instantiates the follow camera.
* @see https://doc.babylonjs.com/features/cameras#follow-camera
* @param name Define the name of the camera in the scene
* @param position Define the position of the camera
* @param scene Define the scene the camera belong to
* @param lockedTarget Define the target of the camera
*/
function FollowCamera(name, position, scene, lockedTarget) {
if (lockedTarget === void 0) { lockedTarget = null; }
var _this = _super.call(this, name, position, scene) || this;
/**
* Distance the follow camera should follow an object at
*/
_this.radius = 12;
/**
* Minimum allowed distance of the camera to the axis of rotation
* (The camera can not get closer).
* This can help limiting how the Camera is able to move in the scene.
*/
_this.lowerRadiusLimit = null;
/**
* Maximum allowed distance of the camera to the axis of rotation
* (The camera can not get further).
* This can help limiting how the Camera is able to move in the scene.
*/
_this.upperRadiusLimit = null;
/**
* Define a rotation offset between the camera and the object it follows
*/
_this.rotationOffset = 0;
/**
* Minimum allowed angle to camera position relative to target object.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.lowerRotationOffsetLimit = null;
/**
* Maximum allowed angle to camera position relative to target object.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.upperRotationOffsetLimit = null;
/**
* Define a height offset between the camera and the object it follows.
* It can help following an object from the top (like a car chaing a plane)
*/
_this.heightOffset = 4;
/**
* Minimum allowed height of camera position relative to target object.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.lowerHeightOffsetLimit = null;
/**
* Maximum allowed height of camera position relative to target object.
* This can help limiting how the Camera is able to move in the scene.
*/
_this.upperHeightOffsetLimit = null;
/**
* Define how fast the camera can accelerate to follow it s target.
*/
_this.cameraAcceleration = 0.05;
/**
* Define the speed limit of the camera following an object.
*/
_this.maxCameraSpeed = 20;
_this.lockedTarget = lockedTarget;
_this.inputs = new _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_6__["FollowCameraInputsManager"](_this);
_this.inputs.addKeyboard().addMouseWheel().addPointers();
return _this;
// Uncomment the following line when the relevant handlers have been implemented.
// this.inputs.addKeyboard().addMouseWheel().addPointers().addVRDeviceOrientation();
}
FollowCamera.prototype._follow = function (cameraTarget) {
if (!cameraTarget) {
return;
}
var yRotation;
if (cameraTarget.rotationQuaternion) {
var rotMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"]();
cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
}
else {
yRotation = cameraTarget.rotation.y;
}
var radians = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].ToRadians(this.rotationOffset) + yRotation;
var targetPosition = cameraTarget.getAbsolutePosition();
var targetX = targetPosition.x + Math.sin(radians) * this.radius;
var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
var dx = targetX - this.position.x;
var dy = (targetPosition.y + this.heightOffset) - this.position.y;
var dz = (targetZ) - this.position.z;
var vx = dx * this.cameraAcceleration * 2; //this is set to .05
var vy = dy * this.cameraAcceleration;
var vz = dz * this.cameraAcceleration * 2;
if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
}
if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
}
if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
}
this.position = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"](this.position.x + vx, this.position.y + vy, this.position.z + vz);
this.setTarget(targetPosition);
};
/**
* Attached controls to the current camera.
* @param element Defines the element the controls should be listened from
* @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
*/
FollowCamera.prototype.attachControl = function (element, noPreventDefault) {
this.inputs.attachElement(element, noPreventDefault);
this._reset = function () {
};
};
/**
* Detach the current controls from the camera.
* The camera will stop reacting to inputs.
* @param element Defines the element to stop listening the inputs from
*/
FollowCamera.prototype.detachControl = function (element) {
this.inputs.detachElement(element);
if (this._reset) {
this._reset();
}
};
/** @hidden */
FollowCamera.prototype._checkInputs = function () {
this.inputs.checkInputs();
this._checkLimits();
_super.prototype._checkInputs.call(this);
if (this.lockedTarget) {
this._follow(this.lockedTarget);
}
};
FollowCamera.prototype._checkLimits = function () {
if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
this.radius = this.lowerRadiusLimit;
}
if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
this.radius = this.upperRadiusLimit;
}
if (this.lowerHeightOffsetLimit !== null &&
this.heightOffset < this.lowerHeightOffsetLimit) {
this.heightOffset = this.lowerHeightOffsetLimit;
}
if (this.upperHeightOffsetLimit !== null &&
this.heightOffset > this.upperHeightOffsetLimit) {
this.heightOffset = this.upperHeightOffsetLimit;
}
if (this.lowerRotationOffsetLimit !== null &&
this.rotationOffset < this.lowerRotationOffsetLimit) {
this.rotationOffset = this.lowerRotationOffsetLimit;
}
if (this.upperRotationOffsetLimit !== null &&
this.rotationOffset > this.upperRotationOffsetLimit) {
this.rotationOffset = this.upperRotationOffsetLimit;
}
};
/**
* Gets the camera class name.
* @returns the class name
*/
FollowCamera.prototype.getClassName = function () {
return "FollowCamera";
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "radius", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "lowerRadiusLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "upperRadiusLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "rotationOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "lowerRotationOffsetLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "upperRotationOffsetLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "heightOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "lowerHeightOffsetLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "upperHeightOffsetLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "cameraAcceleration", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FollowCamera.prototype, "maxCameraSpeed", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMeshReference"])("lockedTargetId")
], FollowCamera.prototype, "lockedTarget", void 0);
return FollowCamera;
}(_targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"]));
/**
* Arc Rotate version of the follow camera.
* It still follows a Defined mesh but in an Arc Rotate Camera fashion.
* @see https://doc.babylonjs.com/features/cameras#follow-camera
*/
var ArcFollowCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ArcFollowCamera, _super);
/**
* Instantiates a new ArcFollowCamera
* @see https://doc.babylonjs.com/features/cameras#follow-camera
* @param name Define the name of the camera
* @param alpha Define the rotation angle of the camera around the logitudinal axis
* @param beta Define the rotation angle of the camera around the elevation axis
* @param radius Define the radius of the camera from its target point
* @param target Define the target of the camera
* @param scene Define the scene the camera belongs to
*/
function ArcFollowCamera(name,
/** The longitudinal angle of the camera */
alpha,
/** The latitudinal angle of the camera */
beta,
/** The radius of the camera from its target */
radius,
/** Define the camera target (the mesh it should follow) */
target, scene) {
var _this = _super.call(this, name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero(), scene) || this;
_this.alpha = alpha;
_this.beta = beta;
_this.radius = radius;
_this._cartesianCoordinates = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero();
_this._meshTarget = target;
_this._follow();
return _this;
}
ArcFollowCamera.prototype._follow = function () {
if (!this._meshTarget) {
return;
}
this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
var targetPosition = this._meshTarget.getAbsolutePosition();
this.position = targetPosition.add(this._cartesianCoordinates);
this.setTarget(targetPosition);
};
/** @hidden */
ArcFollowCamera.prototype._checkInputs = function () {
_super.prototype._checkInputs.call(this);
this._follow();
};
/**
* Returns the class name of the object.
* It is mostly used internally for serialization purposes.
*/
ArcFollowCamera.prototype.getClassName = function () {
return "ArcFollowCamera";
};
return ArcFollowCamera;
}(_targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"]));
/***/ }),
/***/ "./Cameras/followCameraInputsManager.ts":
/*!**********************************************!*\
!*** ./Cameras/followCameraInputsManager.ts ***!
\**********************************************/
/*! exports provided: FollowCameraInputsManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FollowCameraInputsManager", function() { return FollowCameraInputsManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts");
/* harmony import */ var _Inputs_followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Inputs/followCameraKeyboardMoveInput */ "./Cameras/Inputs/followCameraKeyboardMoveInput.ts");
/* harmony import */ var _Inputs_followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Inputs/followCameraMouseWheelInput */ "./Cameras/Inputs/followCameraMouseWheelInput.ts");
/* harmony import */ var _Inputs_followCameraPointersInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/followCameraPointersInput */ "./Cameras/Inputs/followCameraPointersInput.ts");
/**
* Default Inputs manager for the FollowCamera.
* It groups all the default supported inputs for ease of use.
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
*/
var FollowCameraInputsManager = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FollowCameraInputsManager, _super);
/**
* Instantiates a new FollowCameraInputsManager.
* @param camera Defines the camera the inputs belong to
*/
function FollowCameraInputsManager(camera) {
return _super.call(this, camera) || this;
}
/**
* Add keyboard input support to the input manager.
* @returns the current input manager
*/
FollowCameraInputsManager.prototype.addKeyboard = function () {
this.add(new _Inputs_followCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["FollowCameraKeyboardMoveInput"]());
return this;
};
/**
* Add mouse wheel input support to the input manager.
* @returns the current input manager
*/
FollowCameraInputsManager.prototype.addMouseWheel = function () {
this.add(new _Inputs_followCameraMouseWheelInput__WEBPACK_IMPORTED_MODULE_3__["FollowCameraMouseWheelInput"]());
return this;
};
/**
* Add pointers input support to the input manager.
* @returns the current input manager
*/
FollowCameraInputsManager.prototype.addPointers = function () {
this.add(new _Inputs_followCameraPointersInput__WEBPACK_IMPORTED_MODULE_4__["FollowCameraPointersInput"]());
return this;
};
/**
* Add orientation input support to the input manager.
* @returns the current input manager
*/
FollowCameraInputsManager.prototype.addVRDeviceOrientation = function () {
console.warn("DeviceOrientation support not yet implemented for FollowCamera.");
return this;
};
return FollowCameraInputsManager;
}(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"]));
/***/ }),
/***/ "./Cameras/freeCamera.ts":
/*!*******************************!*\
!*** ./Cameras/freeCamera.ts ***!
\*******************************/
/*! exports provided: FreeCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return FreeCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts");
/* harmony import */ var _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts");
/**
* This represents a free type of camera. It can be useful in First Person Shooter game for instance.
* Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
*/
var FreeCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FreeCamera, _super);
/**
* Instantiates a Free Camera.
* This represents a free type of camera. It can be useful in First Person Shooter game for instance.
* Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
* @param name Define the name of the camera in the scene
* @param position Define the start position of the camera in the scene
* @param scene Define the scene the camera belongs to
* @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
*/
function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
/**
* Define the collision ellipsoid of the camera.
* This is helpful to simulate a camera body like the player body around the camera
* @see https://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
*/
_this.ellipsoid = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.5, 1, 0.5);
/**
* Define an offset for the position of the ellipsoid around the camera.
* This can be helpful to determine the center of the body near the gravity center of the body
* instead of its head.
*/
_this.ellipsoidOffset = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0);
/**
* Enable or disable collisions of the camera with the rest of the scene objects.
*/
_this.checkCollisions = false;
/**
* Enable or disable gravity on the camera.
*/
_this.applyGravity = false;
_this._needMoveForGravity = false;
_this._oldPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._diffPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._newPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
// Collisions
_this._collisionMask = -1;
_this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
if (collidedMesh === void 0) { collidedMesh = null; }
var updatePosition = function (newPos) {
_this._newPosition.copyFrom(newPos);
_this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
if (_this._diffPosition.length() > _Engines_engine__WEBPACK_IMPORTED_MODULE_3__["Engine"].CollisionsEpsilon) {
_this.position.addInPlace(_this._diffPosition);
if (_this.onCollide && collidedMesh) {
_this.onCollide(collidedMesh);
}
}
};
updatePosition(newPosition);
};
_this.inputs = new _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FreeCameraInputsManager"](_this);
_this.inputs.addKeyboard().addMouse();
return _this;
}
Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
/**
* Gets the input sensibility for a mouse input. (default is 2000.0)
* Higher values reduce sensitivity.
*/
get: function () {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
return mouse.angularSensibility;
}
return 0;
},
/**
* Sets the input sensibility for a mouse input. (default is 2000.0)
* Higher values reduce sensitivity.
*/
set: function (value) {
var mouse = this.inputs.attached["mouse"];
if (mouse) {
mouse.angularSensibility = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysUp", {
/**
* Gets or Set the list of keyboard keys used to control the forward move of the camera.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysUp;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysUp = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysUpward", {
/**
* Gets or Set the list of keyboard keys used to control the upward move of the camera.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysUpward;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysUpward = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysDown", {
/**
* Gets or Set the list of keyboard keys used to control the backward move of the camera.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysDown;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysDown = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysDownward", {
/**
* Gets or Set the list of keyboard keys used to control the downward move of the camera.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysDownward;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysDownward = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysLeft", {
/**
* Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysLeft;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysLeft = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(FreeCamera.prototype, "keysRight", {
/**
* Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
*/
get: function () {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
return keyboard.keysRight;
}
return [];
},
set: function (value) {
var keyboard = this.inputs.attached["keyboard"];
if (keyboard) {
keyboard.keysRight = value;
}
},
enumerable: false,
configurable: true
});
/**
* Attached controls to the current camera.
* @param element Defines the element the controls should be listened from
* @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
*/
FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
this.inputs.attachElement(element, noPreventDefault);
};
/**
* Detach the current controls from the camera.
* The camera will stop reacting to inputs.
* @param element Defines the element to stop listening the inputs from
*/
FreeCamera.prototype.detachControl = function (element) {
this.inputs.detachElement(element);
this.cameraDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0);
this.cameraRotation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0);
};
Object.defineProperty(FreeCamera.prototype, "collisionMask", {
/**
* Define a collision mask to limit the list of object the camera can collide with
*/
get: function () {
return this._collisionMask;
},
set: function (mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: false,
configurable: true
});
/** @hidden */
FreeCamera.prototype._collideWithWorld = function (displacement) {
var globalPosition;
if (this.parent) {
globalPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(this.position, this.parent.getWorldMatrix());
}
else {
globalPosition = this.position;
}
globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
this._oldPosition.addInPlace(this.ellipsoidOffset);
var coordinator = this.getScene().collisionCoordinator;
if (!this._collider) {
this._collider = coordinator.createCollider();
}
this._collider._radius = this.ellipsoid;
this._collider.collisionMask = this._collisionMask;
//no need for clone, as long as gravity is not on.
var actualDisplacement = displacement;
//add gravity to the direction to prevent the dual-collision checking
if (this.applyGravity) {
//this prevents mending with cameraDirection, a global variable of the free camera class.
actualDisplacement = displacement.add(this.getScene().gravity);
}
coordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
};
/** @hidden */
FreeCamera.prototype._checkInputs = function () {
if (!this._localDirection) {
this._localDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
this._transformedDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
}
this.inputs.checkInputs();
_super.prototype._checkInputs.call(this);
};
/** @hidden */
FreeCamera.prototype._decideIfNeedsToMove = function () {
return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
/** @hidden */
FreeCamera.prototype._updatePosition = function () {
if (this.checkCollisions && this.getScene().collisionsEnabled) {
this._collideWithWorld(this.cameraDirection);
}
else {
_super.prototype._updatePosition.call(this);
}
};
/**
* Destroy the camera and release the current resources hold by it.
*/
FreeCamera.prototype.dispose = function () {
this.inputs.clear();
_super.prototype.dispose.call(this);
};
/**
* Gets the current object class name.
* @return the class name
*/
FreeCamera.prototype.getClassName = function () {
return "FreeCamera";
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], FreeCamera.prototype, "ellipsoid", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], FreeCamera.prototype, "ellipsoidOffset", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FreeCamera.prototype, "checkCollisions", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], FreeCamera.prototype, "applyGravity", void 0);
return FreeCamera;
}(_targetCamera__WEBPACK_IMPORTED_MODULE_4__["TargetCamera"]));
/***/ }),
/***/ "./Cameras/freeCameraInputsManager.ts":
/*!********************************************!*\
!*** ./Cameras/freeCameraInputsManager.ts ***!
\********************************************/
/*! exports provided: FreeCameraInputsManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return FreeCameraInputsManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts");
/* harmony import */ var _Cameras_Inputs_freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraKeyboardMoveInput */ "./Cameras/Inputs/freeCameraKeyboardMoveInput.ts");
/* harmony import */ var _Cameras_Inputs_freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraMouseInput */ "./Cameras/Inputs/freeCameraMouseInput.ts");
/* harmony import */ var _Cameras_Inputs_freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraTouchInput */ "./Cameras/Inputs/freeCameraTouchInput.ts");
/**
* Default Inputs manager for the FreeCamera.
* It groups all the default supported inputs for ease of use.
* @see https://doc.babylonjs.com/how_to/customizing_camera_inputs
*/
var FreeCameraInputsManager = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FreeCameraInputsManager, _super);
/**
* Instantiates a new FreeCameraInputsManager.
* @param camera Defines the camera the inputs belong to
*/
function FreeCameraInputsManager(camera) {
var _this = _super.call(this, camera) || this;
/**
* @hidden
*/
_this._mouseInput = null;
return _this;
}
/**
* Add keyboard input support to the input manager.
* @returns the current input manager
*/
FreeCameraInputsManager.prototype.addKeyboard = function () {
this.add(new _Cameras_Inputs_freeCameraKeyboardMoveInput__WEBPACK_IMPORTED_MODULE_2__["FreeCameraKeyboardMoveInput"]());
return this;
};
/**
* Add mouse input support to the input manager.
* @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
* @returns the current input manager
*/
FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
if (touchEnabled === void 0) { touchEnabled = true; }
if (!this._mouseInput) {
this._mouseInput = new _Cameras_Inputs_freeCameraMouseInput__WEBPACK_IMPORTED_MODULE_3__["FreeCameraMouseInput"](touchEnabled);
this.add(this._mouseInput);
}
return this;
};
/**
* Removes the mouse input support from the manager
* @returns the current input manager
*/
FreeCameraInputsManager.prototype.removeMouse = function () {
if (this._mouseInput) {
this.remove(this._mouseInput);
}
return this;
};
/**
* Add touch input support to the input manager.
* @returns the current input manager
*/
FreeCameraInputsManager.prototype.addTouch = function () {
this.add(new _Cameras_Inputs_freeCameraTouchInput__WEBPACK_IMPORTED_MODULE_4__["FreeCameraTouchInput"]());
return this;
};
/**
* Remove all attached input methods from a camera
*/
FreeCameraInputsManager.prototype.clear = function () {
_super.prototype.clear.call(this);
this._mouseInput = null;
};
return FreeCameraInputsManager;
}(_cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"]));
/***/ }),
/***/ "./Cameras/gamepadCamera.ts":
/*!**********************************!*\
!*** ./Cameras/gamepadCamera.ts ***!
\**********************************/
/*! exports provided: GamepadCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return GamepadCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _universalCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./universalCamera */ "./Cameras/universalCamera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("GamepadCamera", function (name, scene) {
return function () { return new GamepadCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
/**
* This represents a FPS type of camera. This is only here for back compat purpose.
* Please use the UniversalCamera instead as both are identical.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
*/
var GamepadCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GamepadCamera, _super);
/**
* Instantiates a new Gamepad Camera
* This represents a FPS type of camera. This is only here for back compat purpose.
* Please use the UniversalCamera instead as both are identical.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
* @param name Define the name of the camera in the scene
* @param position Define the start position of the camera in the scene
* @param scene Define the scene the camera belongs to
*/
function GamepadCamera(name, position, scene) {
return _super.call(this, name, position, scene) || this;
}
/**
* Gets the current object class name.
* @return the class name
*/
GamepadCamera.prototype.getClassName = function () {
return "GamepadCamera";
};
return GamepadCamera;
}(_universalCamera__WEBPACK_IMPORTED_MODULE_1__["UniversalCamera"]));
/***/ }),
/***/ "./Cameras/index.ts":
/*!**************************!*\
!*** ./Cameras/index.ts ***!
\**************************/
/*! exports provided: ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, CameraInputTypes, CameraInputsManager, Camera, TargetCamera, FreeCamera, FreeCameraInputsManager, TouchCamera, ArcRotateCamera, ArcRotateCameraInputsManager, DeviceOrientationCamera, FlyCamera, FlyCameraInputsManager, FollowCamera, ArcFollowCamera, FollowCameraInputsManager, GamepadCamera, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera, UniversalCamera, VirtualJoysticksCamera, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Inputs_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Inputs/index */ "./Cameras/Inputs/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraKeyboardMoveInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraMouseWheelInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraPointersInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraVRDeviceOrientationInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraKeyboardInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraMouseInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraKeyboardMoveInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraMouseWheelInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraPointersInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraDeviceOrientationInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraGamepadInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraKeyboardMoveInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraMouseInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraTouchInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _Inputs_index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraVirtualJoystickInput"]; });
/* harmony import */ var _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cameraInputsManager */ "./Cameras/cameraInputsManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return _cameraInputsManager__WEBPACK_IMPORTED_MODULE_1__["CameraInputsManager"]; });
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"]; });
/* harmony import */ var _targetCamera__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./targetCamera */ "./Cameras/targetCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return _targetCamera__WEBPACK_IMPORTED_MODULE_3__["TargetCamera"]; });
/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return _freeCamera__WEBPACK_IMPORTED_MODULE_4__["FreeCamera"]; });
/* harmony import */ var _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return _freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["FreeCameraInputsManager"]; });
/* harmony import */ var _touchCamera__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./touchCamera */ "./Cameras/touchCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return _touchCamera__WEBPACK_IMPORTED_MODULE_6__["TouchCamera"]; });
/* harmony import */ var _arcRotateCamera__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./arcRotateCamera */ "./Cameras/arcRotateCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return _arcRotateCamera__WEBPACK_IMPORTED_MODULE_7__["ArcRotateCamera"]; });
/* harmony import */ var _arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return _arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_8__["ArcRotateCameraInputsManager"]; });
/* harmony import */ var _deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./deviceOrientationCamera */ "./Cameras/deviceOrientationCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return _deviceOrientationCamera__WEBPACK_IMPORTED_MODULE_9__["DeviceOrientationCamera"]; });
/* harmony import */ var _flyCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./flyCamera */ "./Cameras/flyCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return _flyCamera__WEBPACK_IMPORTED_MODULE_10__["FlyCamera"]; });
/* harmony import */ var _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./flyCameraInputsManager */ "./Cameras/flyCameraInputsManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return _flyCameraInputsManager__WEBPACK_IMPORTED_MODULE_11__["FlyCameraInputsManager"]; });
/* harmony import */ var _followCamera__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./followCamera */ "./Cameras/followCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return _followCamera__WEBPACK_IMPORTED_MODULE_12__["FollowCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return _followCamera__WEBPACK_IMPORTED_MODULE_12__["ArcFollowCamera"]; });
/* harmony import */ var _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./followCameraInputsManager */ "./Cameras/followCameraInputsManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraInputsManager", function() { return _followCameraInputsManager__WEBPACK_IMPORTED_MODULE_13__["FollowCameraInputsManager"]; });
/* harmony import */ var _gamepadCamera__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./gamepadCamera */ "./Cameras/gamepadCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return _gamepadCamera__WEBPACK_IMPORTED_MODULE_14__["GamepadCamera"]; });
/* harmony import */ var _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Stereoscopic/index */ "./Cameras/Stereoscopic/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["AnaglyphArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["AnaglyphFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["AnaglyphGamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["AnaglyphUniversalCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["StereoscopicArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["StereoscopicFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["StereoscopicGamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _Stereoscopic_index__WEBPACK_IMPORTED_MODULE_15__["StereoscopicUniversalCamera"]; });
/* harmony import */ var _universalCamera__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./universalCamera */ "./Cameras/universalCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return _universalCamera__WEBPACK_IMPORTED_MODULE_16__["UniversalCamera"]; });
/* harmony import */ var _virtualJoysticksCamera__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./virtualJoysticksCamera */ "./Cameras/virtualJoysticksCamera.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return _virtualJoysticksCamera__WEBPACK_IMPORTED_MODULE_17__["VirtualJoysticksCamera"]; });
/* harmony import */ var _VR_index__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./VR/index */ "./Cameras/VR/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["VRCameraMetrics"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["VRDeviceOrientationArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["VRDeviceOrientationFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["VRDeviceOrientationGamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["OnAfterEnteringVRObservableEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["VRExperienceHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _VR_index__WEBPACK_IMPORTED_MODULE_18__["WebVRFreeCamera"]; });
/* harmony import */ var _RigModes_index__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./RigModes/index */ "./Cameras/RigModes/index.ts");
/* empty/unused harmony star reexport */
/***/ }),
/***/ "./Cameras/targetCamera.ts":
/*!*********************************!*\
!*** ./Cameras/targetCamera.ts ***!
\*********************************/
/*! exports provided: TargetCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return TargetCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.constants */ "./Maths/math.constants.ts");
/* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts");
/**
* A target camera takes a mesh or position as a target and continues to look at it while it moves.
* This is the base of the follow, arc rotate cameras and Free camera
* @see https://doc.babylonjs.com/features/cameras
*/
var TargetCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TargetCamera, _super);
/**
* Instantiates a target camera that takes a mesh or position as a target and continues to look at it while it moves.
* This is the base of the follow, arc rotate cameras and Free camera
* @see https://doc.babylonjs.com/features/cameras
* @param name Defines the name of the camera in the scene
* @param position Defines the start position of the camera in the scene
* @param scene Defines the scene the camera belongs to
* @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
*/
function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
_this._tmpUpVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
_this._tmpTargetVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
/**
* Define the current direction the camera is moving to
*/
_this.cameraDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0);
/**
* Define the current rotation the camera is rotating to
*/
_this.cameraRotation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 0);
/** Gets or sets a boolean indicating that the scaling of the parent hierarchy will not be taken in account by the camera */
_this.ignoreParentScaling = false;
/**
* When set, the up vector of the camera will be updated by the rotation of the camera
*/
_this.updateUpVectorFromRotation = false;
_this._tmpQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
/**
* Define the current rotation of the camera
*/
_this.rotation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0);
/**
* Define the current speed of the camera
*/
_this.speed = 2.0;
/**
* Add constraint to the camera to prevent it to move freely in all directions and
* around all axis.
*/
_this.noRotationConstraint = false;
/**
* Reverses mouselook direction to 'natural' panning as opposed to traditional direct
* panning
*/
_this.invertRotation = false;
/**
* Speed multiplier for inverse camera panning
*/
_this.inverseRotationSpeed = 0.2;
/**
* Define the current target of the camera as an object or a position.
*/
_this.lockedTarget = null;
/** @hidden */
_this._currentTarget = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
/** @hidden */
_this._initialFocalDistance = 1;
/** @hidden */
_this._viewMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero();
/** @hidden */
_this._camMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero();
/** @hidden */
_this._cameraTransformMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero();
/** @hidden */
_this._cameraRotationMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].Zero();
/** @hidden */
_this._referencePoint = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1);
/** @hidden */
_this._transformedReferencePoint = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
_this._defaultUp = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up();
_this._cachedRotationZ = 0;
_this._cachedQuaternionRotationZ = 0;
return _this;
}
/**
* Gets the position in front of the camera at a given distance.
* @param distance The distance from the camera we want the position to be
* @returns the position
*/
TargetCamera.prototype.getFrontPosition = function (distance) {
this.getWorldMatrix();
var direction = this.getTarget().subtract(this.position);
direction.normalize();
direction.scaleInPlace(distance);
return this.globalPosition.add(direction);
};
/** @hidden */
TargetCamera.prototype._getLockedTargetPosition = function () {
if (!this.lockedTarget) {
return null;
}
if (this.lockedTarget.absolutePosition) {
this.lockedTarget.computeWorldMatrix();
}
return this.lockedTarget.absolutePosition || this.lockedTarget;
};
/**
* Store current camera state of the camera (fov, position, rotation, etc..)
* @returns the camera
*/
TargetCamera.prototype.storeState = function () {
this._storedPosition = this.position.clone();
this._storedRotation = this.rotation.clone();
if (this.rotationQuaternion) {
this._storedRotationQuaternion = this.rotationQuaternion.clone();
}
return _super.prototype.storeState.call(this);
};
/**
* Restored camera state. You must call storeState() first
* @returns whether it was successful or not
* @hidden
*/
TargetCamera.prototype._restoreStateValues = function () {
if (!_super.prototype._restoreStateValues.call(this)) {
return false;
}
this.position = this._storedPosition.clone();
this.rotation = this._storedRotation.clone();
if (this.rotationQuaternion) {
this.rotationQuaternion = this._storedRotationQuaternion.clone();
}
this.cameraDirection.copyFromFloats(0, 0, 0);
this.cameraRotation.copyFromFloats(0, 0);
return true;
};
/** @hidden */
TargetCamera.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache.lockedTarget = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.rotation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cache.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
};
/** @hidden */
TargetCamera.prototype._updateCache = function (ignoreParentClass) {
if (!ignoreParentClass) {
_super.prototype._updateCache.call(this);
}
var lockedTargetPosition = this._getLockedTargetPosition();
if (!lockedTargetPosition) {
this._cache.lockedTarget = null;
}
else {
if (!this._cache.lockedTarget) {
this._cache.lockedTarget = lockedTargetPosition.clone();
}
else {
this._cache.lockedTarget.copyFrom(lockedTargetPosition);
}
}
this._cache.rotation.copyFrom(this.rotation);
if (this.rotationQuaternion) {
this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
}
};
// Synchronized
/** @hidden */
TargetCamera.prototype._isSynchronizedViewMatrix = function () {
if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
return false;
}
var lockedTargetPosition = this._getLockedTargetPosition();
return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
&& (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
};
// Methods
/** @hidden */
TargetCamera.prototype._computeLocalCameraSpeed = function () {
var engine = this.getEngine();
return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
};
// Target
/**
* Defines the target the camera should look at.
* @param target Defines the new target as a Vector or a mesh
*/
TargetCamera.prototype.setTarget = function (target) {
this.upVector.normalize();
this._initialFocalDistance = target.subtract(this.position).length();
if (this.position.z === target.z) {
this.position.z += _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__["Epsilon"];
}
this._referencePoint.normalize().scaleInPlace(this._initialFocalDistance);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
this._camMatrix.invert();
this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
var vDir = target.subtract(this.position);
if (vDir.x >= 0.0) {
this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
}
else {
this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
}
this.rotation.z = 0;
if (isNaN(this.rotation.x)) {
this.rotation.x = 0;
}
if (isNaN(this.rotation.y)) {
this.rotation.y = 0;
}
if (isNaN(this.rotation.z)) {
this.rotation.z = 0;
}
if (this.rotationQuaternion) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
}
};
Object.defineProperty(TargetCamera.prototype, "target", {
/**
* Defines the target point of the camera.
* The camera looks towards it form the radius distance.
*/
get: function () {
return this.getTarget();
},
set: function (value) {
this.setTarget(value);
},
enumerable: false,
configurable: true
});
/**
* Return the current target position of the camera. This value is expressed in local space.
* @returns the target position
*/
TargetCamera.prototype.getTarget = function () {
return this._currentTarget;
};
/** @hidden */
TargetCamera.prototype._decideIfNeedsToMove = function () {
return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
};
/** @hidden */
TargetCamera.prototype._updatePosition = function () {
if (this.parent) {
this.parent.getWorldMatrix().invertToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["TmpVectors"].Matrix[0]);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this.cameraDirection, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["TmpVectors"].Matrix[0], _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["TmpVectors"].Vector3[0]);
this.position.addInPlace(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["TmpVectors"].Vector3[0]);
return;
}
this.position.addInPlace(this.cameraDirection);
};
/** @hidden */
TargetCamera.prototype._checkInputs = function () {
var directionMultiplier = this.invertRotation ? -this.inverseRotationSpeed : 1.0;
var needToMove = this._decideIfNeedsToMove();
var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
// Move
if (needToMove) {
this._updatePosition();
}
// Rotate
if (needToRotate) {
//rotate, if quaternion is set and rotation was used
if (this.rotationQuaternion) {
this.rotationQuaternion.toEulerAnglesToRef(this.rotation);
}
this.rotation.x += this.cameraRotation.x * directionMultiplier;
this.rotation.y += this.cameraRotation.y * directionMultiplier;
// Apply constraints
if (!this.noRotationConstraint) {
var limit = 1.570796;
if (this.rotation.x > limit) {
this.rotation.x = limit;
}
if (this.rotation.x < -limit) {
this.rotation.x = -limit;
}
}
//rotate, if quaternion is set and rotation was used
if (this.rotationQuaternion) {
var len = this.rotation.lengthSquared();
if (len) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
}
}
}
// Inertia
if (needToMove) {
if (Math.abs(this.cameraDirection.x) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__["Epsilon"]) {
this.cameraDirection.x = 0;
}
if (Math.abs(this.cameraDirection.y) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__["Epsilon"]) {
this.cameraDirection.y = 0;
}
if (Math.abs(this.cameraDirection.z) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__["Epsilon"]) {
this.cameraDirection.z = 0;
}
this.cameraDirection.scaleInPlace(this.inertia);
}
if (needToRotate) {
if (Math.abs(this.cameraRotation.x) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__["Epsilon"]) {
this.cameraRotation.x = 0;
}
if (Math.abs(this.cameraRotation.y) < this.speed * _Maths_math_constants__WEBPACK_IMPORTED_MODULE_4__["Epsilon"]) {
this.cameraRotation.y = 0;
}
this.cameraRotation.scaleInPlace(this.inertia);
}
_super.prototype._checkInputs.call(this);
};
TargetCamera.prototype._updateCameraRotationMatrix = function () {
if (this.rotationQuaternion) {
this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
}
else {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
}
};
/**
* Update the up vector to apply the rotation of the camera (So if you changed the camera rotation.z this will let you update the up vector as well)
* @returns the current camera
*/
TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
return this;
};
/** @hidden */
TargetCamera.prototype._getViewMatrix = function () {
if (this.lockedTarget) {
this.setTarget(this._getLockedTargetPosition());
}
// Compute
this._updateCameraRotationMatrix();
// Apply the changed rotation to the upVector
if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
this._rotateUpVectorWithCameraRotationMatrix();
this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
}
else if (this._cachedRotationZ != this.rotation.z) {
this._rotateUpVectorWithCameraRotationMatrix();
this._cachedRotationZ = this.rotation.z;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
// Computing target and final matrix
this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
if (this.updateUpVectorFromRotation) {
if (this.rotationQuaternion) {
_Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].Y.rotateByQuaternionToRef(this.rotationQuaternion, this.upVector);
}
else {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].FromEulerVectorToRef(this.rotation, this._tmpQuaternion);
_Maths_math_axis__WEBPACK_IMPORTED_MODULE_5__["Axis"].Y.rotateByQuaternionToRef(this._tmpQuaternion, this.upVector);
}
}
this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
return this._viewMatrix;
};
TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
if (this.ignoreParentScaling) {
if (this.parent) {
var parentWorldMatrix = this.parent.getWorldMatrix();
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(target, parentWorldMatrix, this._tmpTargetVector);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormalToRef(up, parentWorldMatrix, this._tmpUpVector);
this._markSyncedWithParent();
}
else {
this._globalPosition.copyFrom(position);
this._tmpTargetVector.copyFrom(target);
this._tmpUpVector.copyFrom(up);
}
if (this.getScene().useRightHandedSystem) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtRHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
}
else {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(this._globalPosition, this._tmpTargetVector, this._tmpUpVector, this._viewMatrix);
}
return;
}
if (this.getScene().useRightHandedSystem) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtRHToRef(position, target, up, this._viewMatrix);
}
else {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].LookAtLHToRef(position, target, up, this._viewMatrix);
}
if (this.parent) {
var parentWorldMatrix = this.parent.getWorldMatrix();
this._viewMatrix.invert();
this._viewMatrix.multiplyToRef(parentWorldMatrix, this._viewMatrix);
this._viewMatrix.getTranslationToRef(this._globalPosition);
this._viewMatrix.invert();
this._markSyncedWithParent();
}
else {
this._globalPosition.copyFrom(position);
}
};
/**
* @hidden
*/
TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
if (this.cameraRigMode !== _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_NONE) {
var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
rigCamera.isRigCamera = true;
rigCamera.rigParent = this;
if (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_VR || this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_WEBVR) {
if (!this.rotationQuaternion) {
this.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
}
rigCamera._cameraRigParams = {};
rigCamera.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
}
return rigCamera;
}
return null;
};
/**
* @hidden
*/
TargetCamera.prototype._updateRigCameras = function () {
var camLeft = this._rigCameras[0];
var camRight = this._rigCameras[1];
this.computeWorldMatrix();
switch (this.cameraRigMode) {
case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_ANAGLYPH:
case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_OVERUNDER:
case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_INTERLACED:
//provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
var leftSign = (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
var rightSign = (this.cameraRigMode === _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft);
this._getRigCamPositionAndTarget(this._cameraRigParams.stereoHalfAngle * rightSign, camRight);
break;
case _camera__WEBPACK_IMPORTED_MODULE_2__["Camera"].RIG_MODE_VR:
if (camLeft.rotationQuaternion) {
camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
}
else {
camLeft.rotation.copyFrom(this.rotation);
camRight.rotation.copyFrom(this.rotation);
}
camLeft.position.copyFrom(this.position);
camRight.position.copyFrom(this.position);
break;
}
_super.prototype._updateRigCameras.call(this);
};
TargetCamera.prototype._getRigCamPositionAndTarget = function (halfSpace, rigCamera) {
var target = this.getTarget();
target.subtractToRef(this.position, TargetCamera._TargetFocalPoint);
TargetCamera._TargetFocalPoint.normalize().scaleInPlace(this._initialFocalDistance);
var newFocalTarget = TargetCamera._TargetFocalPoint.addInPlace(this.position);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].TranslationToRef(-newFocalTarget.x, -newFocalTarget.y, -newFocalTarget.z, TargetCamera._TargetTransformMatrix);
TargetCamera._TargetTransformMatrix.multiplyToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].RotationAxis(rigCamera.upVector, halfSpace), TargetCamera._RigCamTransformMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"].TranslationToRef(newFocalTarget.x, newFocalTarget.y, newFocalTarget.z, TargetCamera._TargetTransformMatrix);
TargetCamera._RigCamTransformMatrix.multiplyToRef(TargetCamera._TargetTransformMatrix, TargetCamera._RigCamTransformMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(this.position, TargetCamera._RigCamTransformMatrix, rigCamera.position);
rigCamera.setTarget(newFocalTarget);
};
/**
* Gets the current object class name.
* @return the class name
*/
TargetCamera.prototype.getClassName = function () {
return "TargetCamera";
};
TargetCamera._RigCamTransformMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
TargetCamera._TargetTransformMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
TargetCamera._TargetFocalPoint = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"]();
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], TargetCamera.prototype, "rotation", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], TargetCamera.prototype, "speed", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsMeshReference"])("lockedTargetId")
], TargetCamera.prototype, "lockedTarget", void 0);
return TargetCamera;
}(_camera__WEBPACK_IMPORTED_MODULE_2__["Camera"]));
/***/ }),
/***/ "./Cameras/touchCamera.ts":
/*!********************************!*\
!*** ./Cameras/touchCamera.ts ***!
\********************************/
/*! exports provided: TouchCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return TouchCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("TouchCamera", function (name, scene) {
return function () { return new TouchCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
/**
* This represents a FPS type of camera controlled by touch.
* This is like a universal camera minus the Gamepad controls.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
*/
var TouchCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TouchCamera, _super);
/**
* Instantiates a new touch camera.
* This represents a FPS type of camera controlled by touch.
* This is like a universal camera minus the Gamepad controls.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
* @param name Define the name of the camera in the scene
* @param position Define the start position of the camera in the scene
* @param scene Define the scene the camera belongs to
*/
function TouchCamera(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.inputs.addTouch();
_this._setupInputs();
return _this;
}
Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
/**
* Defines the touch sensibility for rotation.
* The higher the faster.
*/
get: function () {
var touch = this.inputs.attached["touch"];
if (touch) {
return touch.touchAngularSensibility;
}
return 0;
},
set: function (value) {
var touch = this.inputs.attached["touch"];
if (touch) {
touch.touchAngularSensibility = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
/**
* Defines the touch sensibility for move.
* The higher the faster.
*/
get: function () {
var touch = this.inputs.attached["touch"];
if (touch) {
return touch.touchMoveSensibility;
}
return 0;
},
set: function (value) {
var touch = this.inputs.attached["touch"];
if (touch) {
touch.touchMoveSensibility = value;
}
},
enumerable: false,
configurable: true
});
/**
* Gets the current object class name.
* @return the class name
*/
TouchCamera.prototype.getClassName = function () {
return "TouchCamera";
};
/** @hidden */
TouchCamera.prototype._setupInputs = function () {
var touch = this.inputs.attached["touch"];
var mouse = this.inputs.attached["mouse"];
if (mouse) {
mouse.touchEnabled = false;
}
else {
touch.allowMouse = true;
}
};
return TouchCamera;
}(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"]));
/***/ }),
/***/ "./Cameras/universalCamera.ts":
/*!************************************!*\
!*** ./Cameras/universalCamera.ts ***!
\************************************/
/*! exports provided: UniversalCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return UniversalCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _touchCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./touchCamera */ "./Cameras/touchCamera.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./camera */ "./Cameras/camera.ts");
/* harmony import */ var _Gamepads_gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Gamepads/gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts");
_node__WEBPACK_IMPORTED_MODULE_2__["Node"].AddNodeConstructor("FreeCamera", function (name, scene) {
// Forcing to use the Universal camera
return function () { return new UniversalCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene); };
});
/**
* The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
* which still works and will still be found in many Playgrounds.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
*/
var UniversalCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(UniversalCamera, _super);
/**
* The Universal Camera is the one to choose for first person shooter type games, and works with all the keyboard, mouse, touch and gamepads. This replaces the earlier Free Camera,
* which still works and will still be found in many Playgrounds.
* @see https://doc.babylonjs.com/features/cameras#universal-camera
* @param name Define the name of the camera in the scene
* @param position Define the start position of the camera in the scene
* @param scene Define the scene the camera belongs to
*/
function UniversalCamera(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.inputs.addGamepad();
return _this;
}
Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
/**
* Defines the gamepad rotation sensiblity.
* This is the threshold from when rotation starts to be accounted for to prevent jittering.
*/
get: function () {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
return gamepad.gamepadAngularSensibility;
}
return 0;
},
set: function (value) {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
gamepad.gamepadAngularSensibility = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
/**
* Defines the gamepad move sensiblity.
* This is the threshold from when moving starts to be accounted for for to prevent jittering.
*/
get: function () {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
return gamepad.gamepadMoveSensibility;
}
return 0;
},
set: function (value) {
var gamepad = this.inputs.attached["gamepad"];
if (gamepad) {
gamepad.gamepadMoveSensibility = value;
}
},
enumerable: false,
configurable: true
});
/**
* Gets the current object class name.
* @return the class name
*/
UniversalCamera.prototype.getClassName = function () {
return "UniversalCamera";
};
return UniversalCamera;
}(_touchCamera__WEBPACK_IMPORTED_MODULE_1__["TouchCamera"]));
_camera__WEBPACK_IMPORTED_MODULE_4__["Camera"]._createDefaultParsedCamera = function (name, scene) {
return new UniversalCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(), scene);
};
/***/ }),
/***/ "./Cameras/virtualJoysticksCamera.ts":
/*!*******************************************!*\
!*** ./Cameras/virtualJoysticksCamera.ts ***!
\*******************************************/
/*! exports provided: VirtualJoysticksCamera */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return VirtualJoysticksCamera; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _freeCamera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./freeCamera */ "./Cameras/freeCamera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _Inputs_freeCameraVirtualJoystickInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Inputs/freeCameraVirtualJoystickInput */ "./Cameras/Inputs/freeCameraVirtualJoystickInput.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
return function () { return new VirtualJoysticksCamera(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
/**
* This represents a free type of camera. It can be useful in First Person Shooter game for instance.
* It is identical to the Free Camera and simply adds by default a virtual joystick.
* Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
* @see https://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
*/
var VirtualJoysticksCamera = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VirtualJoysticksCamera, _super);
/**
* Intantiates a VirtualJoysticksCamera. It can be useful in First Person Shooter game for instance.
* It is identical to the Free Camera and simply adds by default a virtual joystick.
* Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
* @see https://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
* @param name Define the name of the camera in the scene
* @param position Define the start position of the camera in the scene
* @param scene Define the scene the camera belongs to
*/
function VirtualJoysticksCamera(name, position, scene) {
var _this = _super.call(this, name, position, scene) || this;
_this.inputs.addVirtualJoystick();
return _this;
}
/**
* Gets the current object class name.
* @return the class name
*/
VirtualJoysticksCamera.prototype.getClassName = function () {
return "VirtualJoysticksCamera";
};
return VirtualJoysticksCamera;
}(_freeCamera__WEBPACK_IMPORTED_MODULE_1__["FreeCamera"]));
/***/ }),
/***/ "./Collisions/collider.ts":
/*!********************************!*\
!*** ./Collisions/collider.ts ***!
\********************************/
/*! exports provided: Collider */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return Collider; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_plane__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.plane */ "./Maths/math.plane.ts");
var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
if (boxMin.x > sphereCenter.x + sphereRadius) {
return false;
}
if (sphereCenter.x - sphereRadius > boxMax.x) {
return false;
}
if (boxMin.y > sphereCenter.y + sphereRadius) {
return false;
}
if (sphereCenter.y - sphereRadius > boxMax.y) {
return false;
}
if (boxMin.z > sphereCenter.z + sphereRadius) {
return false;
}
if (sphereCenter.z - sphereRadius > boxMax.z) {
return false;
}
return true;
};
var getLowestRoot = (function () {
var result = { root: 0, found: false };
return function (a, b, c, maxR) {
result.root = 0;
result.found = false;
var determinant = b * b - 4.0 * a * c;
if (determinant < 0) {
return result;
}
var sqrtD = Math.sqrt(determinant);
var r1 = (-b - sqrtD) / (2.0 * a);
var r2 = (-b + sqrtD) / (2.0 * a);
if (r1 > r2) {
var temp = r2;
r2 = r1;
r1 = temp;
}
if (r1 > 0 && r1 < maxR) {
result.root = r1;
result.found = true;
return result;
}
if (r2 > 0 && r2 < maxR) {
result.root = r2;
result.found = true;
return result;
}
return result;
};
})();
/** @hidden */
var Collider = /** @class */ (function () {
function Collider() {
// Implementation of the "Improved Collision detection and Response" algorithm proposed by Kasper Fauerby
// https://www.peroxide.dk/papers/collision/collision.pdf
this._collisionPoint = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._planeIntersectionPoint = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._tempVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._tempVector2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._tempVector3 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._tempVector4 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._edge = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._baseToVertex = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._destinationPoint = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._slidePlaneNormal = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._displacementVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
/** @hidden */
this._radius = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].One();
/** @hidden */
this._retry = 0;
/** @hidden */
this._basePointWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._velocityWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._normalizedVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
this._collisionMask = -1;
}
Object.defineProperty(Collider.prototype, "collisionMask", {
get: function () {
return this._collisionMask;
},
set: function (mask) {
this._collisionMask = !isNaN(mask) ? mask : -1;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
/**
* Gets the plane normal used to compute the sliding response (in local space)
*/
get: function () {
return this._slidePlaneNormal;
},
enumerable: false,
configurable: true
});
// Methods
/** @hidden */
Collider.prototype._initialize = function (source, dir, e) {
this._velocity = dir;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].NormalizeToRef(dir, this._normalizedVelocity);
this._basePoint = source;
source.multiplyToRef(this._radius, this._basePointWorld);
dir.multiplyToRef(this._radius, this._velocityWorld);
this._velocityWorldLength = this._velocityWorld.length();
this._epsilon = e;
this.collisionFound = false;
};
/** @hidden */
Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
pa.subtractToRef(point, this._tempVector);
pb.subtractToRef(point, this._tempVector2);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
var d = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n);
if (d < 0) {
return false;
}
pc.subtractToRef(point, this._tempVector3);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
d = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n);
if (d < 0) {
return false;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
d = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._tempVector4, n);
return d >= 0;
};
/** @hidden */
Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
var distance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(this._basePointWorld, sphereCenter);
var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
if (distance > this._velocityWorldLength + max + sphereRadius) {
return false;
}
if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max)) {
return false;
}
return true;
};
/** @hidden */
Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial, hostMesh) {
var t0;
var embeddedInPlane = false;
//defensive programming, actually not needed.
if (!trianglePlaneArray) {
trianglePlaneArray = [];
}
if (!trianglePlaneArray[faceIndex]) {
trianglePlaneArray[faceIndex] = new _Maths_math_plane__WEBPACK_IMPORTED_MODULE_1__["Plane"](0, 0, 0, 0);
trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
}
var trianglePlane = trianglePlaneArray[faceIndex];
if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0)) {
return;
}
var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
var normalDotVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(trianglePlane.normal, this._velocity);
if (normalDotVelocity == 0) {
if (Math.abs(signedDistToTrianglePlane) >= 1.0) {
return;
}
embeddedInPlane = true;
t0 = 0;
}
else {
t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
if (t0 > t1) {
var temp = t1;
t1 = t0;
t0 = temp;
}
if (t0 > 1.0 || t1 < 0.0) {
return;
}
if (t0 < 0) {
t0 = 0;
}
if (t0 > 1.0) {
t0 = 1.0;
}
}
this._collisionPoint.copyFromFloats(0, 0, 0);
var found = false;
var t = 1.0;
if (!embeddedInPlane) {
this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
this._velocity.scaleToRef(t0, this._tempVector);
this._planeIntersectionPoint.addInPlace(this._tempVector);
if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
found = true;
t = t0;
this._collisionPoint.copyFrom(this._planeIntersectionPoint);
}
}
if (!found) {
var velocitySquaredLength = this._velocity.lengthSquared();
var a = velocitySquaredLength;
this._basePoint.subtractToRef(p1, this._tempVector);
var b = 2.0 * (_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector));
var c = this._tempVector.lengthSquared() - 1.0;
var lowestRoot = getLowestRoot(a, b, c, t);
if (lowestRoot.found) {
t = lowestRoot.root;
found = true;
this._collisionPoint.copyFrom(p1);
}
this._basePoint.subtractToRef(p2, this._tempVector);
b = 2.0 * (_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector));
c = this._tempVector.lengthSquared() - 1.0;
lowestRoot = getLowestRoot(a, b, c, t);
if (lowestRoot.found) {
t = lowestRoot.root;
found = true;
this._collisionPoint.copyFrom(p2);
}
this._basePoint.subtractToRef(p3, this._tempVector);
b = 2.0 * (_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._tempVector));
c = this._tempVector.lengthSquared() - 1.0;
lowestRoot = getLowestRoot(a, b, c, t);
if (lowestRoot.found) {
t = lowestRoot.root;
found = true;
this._collisionPoint.copyFrom(p3);
}
p2.subtractToRef(p1, this._edge);
p1.subtractToRef(this._basePoint, this._baseToVertex);
var edgeSquaredLength = this._edge.lengthSquared();
var edgeDotVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity);
var edgeDotBaseToVertex = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex);
a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
b = edgeSquaredLength * (2.0 * _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
lowestRoot = getLowestRoot(a, b, c, t);
if (lowestRoot.found) {
var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
if (f >= 0.0 && f <= 1.0) {
t = lowestRoot.root;
found = true;
this._edge.scaleInPlace(f);
p1.addToRef(this._edge, this._collisionPoint);
}
}
p3.subtractToRef(p2, this._edge);
p2.subtractToRef(this._basePoint, this._baseToVertex);
edgeSquaredLength = this._edge.lengthSquared();
edgeDotVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity);
edgeDotBaseToVertex = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex);
a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
b = edgeSquaredLength * (2.0 * _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
lowestRoot = getLowestRoot(a, b, c, t);
if (lowestRoot.found) {
f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
if (f >= 0.0 && f <= 1.0) {
t = lowestRoot.root;
found = true;
this._edge.scaleInPlace(f);
p2.addToRef(this._edge, this._collisionPoint);
}
}
p1.subtractToRef(p3, this._edge);
p3.subtractToRef(this._basePoint, this._baseToVertex);
edgeSquaredLength = this._edge.lengthSquared();
edgeDotVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._velocity);
edgeDotBaseToVertex = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._edge, this._baseToVertex);
a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
b = edgeSquaredLength * (2.0 * _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
lowestRoot = getLowestRoot(a, b, c, t);
if (lowestRoot.found) {
f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
if (f >= 0.0 && f <= 1.0) {
t = lowestRoot.root;
found = true;
this._edge.scaleInPlace(f);
p3.addToRef(this._edge, this._collisionPoint);
}
}
}
if (found) {
var distToCollision = t * this._velocity.length();
if (!this.collisionFound || distToCollision < this._nearestDistance) {
if (!this.intersectionPoint) {
this.intersectionPoint = this._collisionPoint.clone();
}
else {
this.intersectionPoint.copyFrom(this._collisionPoint);
}
this._nearestDistance = distToCollision;
this.collisionFound = true;
this.collidedMesh = hostMesh;
}
}
};
/** @hidden */
Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial, hostMesh) {
for (var i = indexStart; i < indexEnd; i += 3) {
var p1 = pts[indices[i] - decal];
var p2 = pts[indices[i + 1] - decal];
var p3 = pts[indices[i + 2] - decal];
this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial, hostMesh);
}
};
/** @hidden */
Collider.prototype._getResponse = function (pos, vel) {
pos.addToRef(vel, this._destinationPoint);
vel.scaleInPlace((this._nearestDistance / vel.length()));
this._basePoint.addToRef(vel, pos);
pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
this._slidePlaneNormal.normalize();
this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
pos.addInPlace(this._displacementVector);
this.intersectionPoint.addInPlace(this._displacementVector);
this._slidePlaneNormal.scaleInPlace(_Maths_math_plane__WEBPACK_IMPORTED_MODULE_1__["Plane"].SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
};
return Collider;
}());
/***/ }),
/***/ "./Collisions/collisionCoordinator.ts":
/*!********************************************!*\
!*** ./Collisions/collisionCoordinator.ts ***!
\********************************************/
/*! exports provided: DefaultCollisionCoordinator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return DefaultCollisionCoordinator; });
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scene */ "./scene.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _collider__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./collider */ "./Collisions/collider.ts");
/** @hidden */
var DefaultCollisionCoordinator = /** @class */ (function () {
function DefaultCollisionCoordinator() {
this._scaledPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
this._scaledVelocity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
this._finalPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
}
DefaultCollisionCoordinator.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
position.divideToRef(collider._radius, this._scaledPosition);
displacement.divideToRef(collider._radius, this._scaledVelocity);
collider.collidedMesh = null;
collider._retry = 0;
collider._initialVelocity = this._scaledVelocity;
collider._initialPosition = this._scaledPosition;
this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
this._finalPosition.multiplyInPlace(collider._radius);
//run the callback
onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
};
DefaultCollisionCoordinator.prototype.createCollider = function () {
return new _collider__WEBPACK_IMPORTED_MODULE_3__["Collider"]();
};
DefaultCollisionCoordinator.prototype.init = function (scene) {
this._scene = scene;
};
DefaultCollisionCoordinator.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
if (excludedMesh === void 0) { excludedMesh = null; }
var closeDistance = _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].CollisionsEpsilon * 10.0;
if (collider._retry >= maximumRetry) {
finalPosition.copyFrom(position);
return;
}
// Check if this is a mesh else camera or -1
var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
collider._initialize(position, velocity, closeDistance);
// Check if collision detection should happen against specified list of meshes or,
// if not specified, against all meshes in the scene
var meshes = (excludedMesh && excludedMesh.surroundingMeshes) || this._scene.meshes;
for (var index = 0; index < meshes.length; index++) {
var mesh = meshes[index];
if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
mesh._checkCollision(collider);
}
}
if (!collider.collisionFound) {
position.addToRef(velocity, finalPosition);
return;
}
if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
collider._getResponse(position, velocity);
}
if (velocity.length() <= closeDistance) {
finalPosition.copyFrom(position);
return;
}
collider._retry++;
this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
};
return DefaultCollisionCoordinator;
}());
_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].CollisionCoordinatorFactory = function () {
return new DefaultCollisionCoordinator();
};
/***/ }),
/***/ "./Collisions/index.ts":
/*!*****************************!*\
!*** ./Collisions/index.ts ***!
\*****************************/
/*! exports provided: Collider, DefaultCollisionCoordinator, PickingInfo, IntersectionInfo, _MeshCollisionData */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _collider__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./collider */ "./Collisions/collider.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _collider__WEBPACK_IMPORTED_MODULE_0__["Collider"]; });
/* harmony import */ var _collisionCoordinator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./collisionCoordinator */ "./Collisions/collisionCoordinator.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return _collisionCoordinator__WEBPACK_IMPORTED_MODULE_1__["DefaultCollisionCoordinator"]; });
/* harmony import */ var _pickingInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pickingInfo */ "./Collisions/pickingInfo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return _pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]; });
/* harmony import */ var _intersectionInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./intersectionInfo */ "./Collisions/intersectionInfo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return _intersectionInfo__WEBPACK_IMPORTED_MODULE_3__["IntersectionInfo"]; });
/* harmony import */ var _meshCollisionData__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./meshCollisionData */ "./Collisions/meshCollisionData.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_MeshCollisionData", function() { return _meshCollisionData__WEBPACK_IMPORTED_MODULE_4__["_MeshCollisionData"]; });
/***/ }),
/***/ "./Collisions/intersectionInfo.ts":
/*!****************************************!*\
!*** ./Collisions/intersectionInfo.ts ***!
\****************************************/
/*! exports provided: IntersectionInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return IntersectionInfo; });
/**
* @hidden
*/
var IntersectionInfo = /** @class */ (function () {
function IntersectionInfo(bu, bv, distance) {
this.bu = bu;
this.bv = bv;
this.distance = distance;
this.faceId = 0;
this.subMeshId = 0;
}
return IntersectionInfo;
}());
/***/ }),
/***/ "./Collisions/meshCollisionData.ts":
/*!*****************************************!*\
!*** ./Collisions/meshCollisionData.ts ***!
\*****************************************/
/*! exports provided: _MeshCollisionData */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_MeshCollisionData", function() { return _MeshCollisionData; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/**
* @hidden
*/
var _MeshCollisionData = /** @class */ (function () {
function _MeshCollisionData() {
this._checkCollisions = false;
this._collisionMask = -1;
this._collisionGroup = -1;
this._surroundingMeshes = null;
this._collider = null;
this._oldPositionForCollisions = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 0);
this._diffPositionForCollisions = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 0);
}
return _MeshCollisionData;
}());
/***/ }),
/***/ "./Collisions/pickingInfo.ts":
/*!***********************************!*\
!*** ./Collisions/pickingInfo.ts ***!
\***********************************/
/*! exports provided: PickingInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return PickingInfo; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/**
* Information about the result of picking within a scene
* @see https://doc.babylonjs.com/babylon101/picking_collisions
*/
var PickingInfo = /** @class */ (function () {
function PickingInfo() {
/** @hidden */
this._pickingUnavailable = false;
/**
* If the pick collided with an object
*/
this.hit = false;
/**
* Distance away where the pick collided
*/
this.distance = 0;
/**
* The location of pick collision
*/
this.pickedPoint = null;
/**
* The mesh corresponding the the pick collision
*/
this.pickedMesh = null;
/** (See getTextureCoordinates) The barycentric U coordinate that is used when calculating the texture coordinates of the collision.*/
this.bu = 0;
/** (See getTextureCoordinates) The barycentric V coordinate that is used when calculating the texture coordinates of the collision.*/
this.bv = 0;
/** The index of the face on the mesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */
this.faceId = -1;
/** The index of the face on the subMesh that was picked, or the index of the Line if the picked Mesh is a LinesMesh */
this.subMeshFaceId = -1;
/** Id of the the submesh that was picked */
this.subMeshId = 0;
/** If a sprite was picked, this will be the sprite the pick collided with */
this.pickedSprite = null;
/** If we are pikcing a mesh with thin instance, this will give you the picked thin instance */
this.thinInstanceIndex = -1;
/**
* If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
*/
this.originMesh = null;
/**
* The ray that was used to perform the picking.
*/
this.ray = null;
}
/**
* Gets the normal correspodning to the face the pick collided with
* @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
* @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
* @returns The normal correspodning to the face the pick collided with
*/
PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
if (useVerticesNormals === void 0) { useVerticesNormals = true; }
if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind)) {
return null;
}
var indices = this.pickedMesh.getIndices();
if (!indices) {
return null;
}
var result;
if (useVerticesNormals) {
var normals = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].NormalKind);
var normal0 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3] * 3);
var normal1 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3 + 1] * 3);
var normal2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(normals, indices[this.faceId * 3 + 2] * 3);
normal0 = normal0.scale(this.bu);
normal1 = normal1.scale(this.bv);
normal2 = normal2.scale(1.0 - this.bu - this.bv);
result = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
}
else {
var positions = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].PositionKind);
var vertex1 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3] * 3);
var vertex2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3 + 1] * 3);
var vertex3 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indices[this.faceId * 3 + 2] * 3);
var p1p2 = vertex1.subtract(vertex2);
var p3p2 = vertex3.subtract(vertex2);
result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(p1p2, p3p2);
}
if (useWorldCoordinates) {
var wm = this.pickedMesh.getWorldMatrix();
if (this.pickedMesh.nonUniformScaling) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Matrix[0].copyFrom(wm);
wm = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Matrix[0];
wm.setTranslationFromFloats(0, 0, 0);
wm.invert();
wm.transposeToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Matrix[1]);
wm = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Matrix[1];
}
result = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformNormal(result, wm);
}
result.normalize();
return result;
};
/**
* Gets the texture coordinates of where the pick occured
* @returns the vector containing the coordnates of the texture
*/
PickingInfo.prototype.getTextureCoordinates = function () {
if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind)) {
return null;
}
var indices = this.pickedMesh.getIndices();
if (!indices) {
return null;
}
var uvs = this.pickedMesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind);
if (!uvs) {
return null;
}
var uv0 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3] * 2);
var uv1 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
var uv2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
uv0 = uv0.scale(this.bu);
uv1 = uv1.scale(this.bv);
uv2 = uv2.scale(1.0 - this.bu - this.bv);
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector2"](uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
};
return PickingInfo;
}());
/***/ }),
/***/ "./Culling/Octrees/index.ts":
/*!**********************************!*\
!*** ./Culling/Octrees/index.ts ***!
\**********************************/
/*! exports provided: Octree, OctreeBlock, OctreeSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _octree__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./octree */ "./Culling/Octrees/octree.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _octree__WEBPACK_IMPORTED_MODULE_0__["Octree"]; });
/* harmony import */ var _octreeBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./octreeBlock */ "./Culling/Octrees/octreeBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _octreeBlock__WEBPACK_IMPORTED_MODULE_1__["OctreeBlock"]; });
/* harmony import */ var _octreeSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./octreeSceneComponent */ "./Culling/Octrees/octreeSceneComponent.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _octreeSceneComponent__WEBPACK_IMPORTED_MODULE_2__["OctreeSceneComponent"]; });
/***/ }),
/***/ "./Culling/Octrees/octree.ts":
/*!***********************************!*\
!*** ./Culling/Octrees/octree.ts ***!
\***********************************/
/*! exports provided: Octree */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return Octree; });
/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts");
/* harmony import */ var _octreeBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./octreeBlock */ "./Culling/Octrees/octreeBlock.ts");
/**
* Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
*/
var Octree = /** @class */ (function () {
/**
* Creates a octree
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
* @param creationFunc function to be used to instatiate the octree
* @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
* @param maxDepth defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.)
*/
function Octree(creationFunc, maxBlockCapacity,
/** Defines the maximum depth (sub-levels) for your octree. Default value is 2, which means 8 8 8 = 512 blocks :) (This parameter takes precedence over capacity.) */
maxDepth) {
if (maxDepth === void 0) { maxDepth = 2; }
this.maxDepth = maxDepth;
/**
* Content stored in the octree
*/
this.dynamicContent = new Array();
this._maxBlockCapacity = maxBlockCapacity || 64;
this._selectionContent = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_0__["SmartArrayNoDuplicate"](1024);
this._creationFunc = creationFunc;
}
// Methods
/**
* Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
* @param worldMin worldMin for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
* @param worldMax worldMax for the octree blocks var blockSize = new Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
* @param entries meshes to be added to the octree blocks
*/
Octree.prototype.update = function (worldMin, worldMax, entries) {
_octreeBlock__WEBPACK_IMPORTED_MODULE_1__["OctreeBlock"]._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
};
/**
* Adds a mesh to the octree
* @param entry Mesh to add to the octree
*/
Octree.prototype.addMesh = function (entry) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.addEntry(entry);
}
};
/**
* Remove an element from the octree
* @param entry defines the element to remove
*/
Octree.prototype.removeMesh = function (entry) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.removeEntry(entry);
}
};
/**
* Selects an array of meshes within the frustum
* @param frustumPlanes The frustum planes to use which will select all meshes within it
* @param allowDuplicate If duplicate objects are allowed in the resulting object array
* @returns array of meshes within the frustum
*/
Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
this._selectionContent.reset();
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.select(frustumPlanes, this._selectionContent, allowDuplicate);
}
if (allowDuplicate) {
this._selectionContent.concat(this.dynamicContent);
}
else {
this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
}
return this._selectionContent;
};
/**
* Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
* @param sphereCenter defines the bounding sphere center
* @param sphereRadius defines the bounding sphere radius
* @param allowDuplicate defines if the selection array can contains duplicated entries
* @returns an array of objects that intersect the sphere
*/
Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
this._selectionContent.reset();
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
}
if (allowDuplicate) {
this._selectionContent.concat(this.dynamicContent);
}
else {
this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
}
return this._selectionContent;
};
/**
* Test if the octree intersect with the given ray and if yes, then add its content to resulting array
* @param ray defines the ray to test with
* @returns array of intersected objects
*/
Octree.prototype.intersectsRay = function (ray) {
this._selectionContent.reset();
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersectsRay(ray, this._selectionContent);
}
this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
return this._selectionContent;
};
/**
* Adds a mesh into the octree block if it intersects the block
*/
Octree.CreationFuncForMeshes = function (entry, block) {
var boundingInfo = entry.getBoundingInfo();
if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
block.entries.push(entry);
}
};
/**
* Adds a submesh into the octree block if it intersects the block
*/
Octree.CreationFuncForSubMeshes = function (entry, block) {
var boundingInfo = entry.getBoundingInfo();
if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
block.entries.push(entry);
}
};
return Octree;
}());
/***/ }),
/***/ "./Culling/Octrees/octreeBlock.ts":
/*!****************************************!*\
!*** ./Culling/Octrees/octreeBlock.ts ***!
\****************************************/
/*! exports provided: OctreeBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return OctreeBlock; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Culling/boundingBox */ "./Culling/boundingBox.ts");
/**
* Class used to store a cell in an octree
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
*/
var OctreeBlock = /** @class */ (function () {
/**
* Creates a new block
* @param minPoint defines the minimum vector (in world space) of the block's bounding box
* @param maxPoint defines the maximum vector (in world space) of the block's bounding box
* @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
* @param depth defines the current depth of this block in the octree
* @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
* @param creationFunc defines a callback to call when an element is added to the block
*/
function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
/**
* Gets the content of the current block
*/
this.entries = new Array();
this._boundingVectors = new Array();
this._capacity = capacity;
this._depth = depth;
this._maxDepth = maxDepth;
this._creationFunc = creationFunc;
this._minPoint = minPoint;
this._maxPoint = maxPoint;
this._boundingVectors.push(minPoint.clone());
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors.push(minPoint.clone());
this._boundingVectors[2].x = maxPoint.x;
this._boundingVectors.push(minPoint.clone());
this._boundingVectors[3].y = maxPoint.y;
this._boundingVectors.push(minPoint.clone());
this._boundingVectors[4].z = maxPoint.z;
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors[5].z = minPoint.z;
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors[6].x = minPoint.x;
this._boundingVectors.push(maxPoint.clone());
this._boundingVectors[7].y = minPoint.y;
}
Object.defineProperty(OctreeBlock.prototype, "capacity", {
// Property
/**
* Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
*/
get: function () {
return this._capacity;
},
enumerable: false,
configurable: true
});
Object.defineProperty(OctreeBlock.prototype, "minPoint", {
/**
* Gets the minimum vector (in world space) of the block's bounding box
*/
get: function () {
return this._minPoint;
},
enumerable: false,
configurable: true
});
Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
/**
* Gets the maximum vector (in world space) of the block's bounding box
*/
get: function () {
return this._maxPoint;
},
enumerable: false,
configurable: true
});
// Methods
/**
* Add a new element to this block
* @param entry defines the element to add
*/
OctreeBlock.prototype.addEntry = function (entry) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.addEntry(entry);
}
return;
}
this._creationFunc(entry, this);
if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
this.createInnerBlocks();
}
};
/**
* Remove an element from this block
* @param entry defines the element to remove
*/
OctreeBlock.prototype.removeEntry = function (entry) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.removeEntry(entry);
}
return;
}
var entryIndex = this.entries.indexOf(entry);
if (entryIndex > -1) {
this.entries.splice(entryIndex, 1);
}
};
/**
* Add an array of elements to this block
* @param entries defines the array of elements to add
*/
OctreeBlock.prototype.addEntries = function (entries) {
for (var index = 0; index < entries.length; index++) {
var mesh = entries[index];
this.addEntry(mesh);
}
};
/**
* Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
* @param frustumPlanes defines the frustum planes to test
* @param selection defines the array to store current content if selection is positive
* @param allowDuplicate defines if the selection array can contains duplicated entries
*/
OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
if (_Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"].IsInFrustum(this._boundingVectors, frustumPlanes)) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.select(frustumPlanes, selection, allowDuplicate);
}
return;
}
if (allowDuplicate) {
selection.concat(this.entries);
}
else {
selection.concatWithNoDuplicate(this.entries);
}
}
};
/**
* Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
* @param sphereCenter defines the bounding sphere center
* @param sphereRadius defines the bounding sphere radius
* @param selection defines the array to store current content if selection is positive
* @param allowDuplicate defines if the selection array can contains duplicated entries
*/
OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
if (_Culling_boundingBox__WEBPACK_IMPORTED_MODULE_1__["BoundingBox"].IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
}
return;
}
if (allowDuplicate) {
selection.concat(this.entries);
}
else {
selection.concatWithNoDuplicate(this.entries);
}
}
};
/**
* Test if the current block intersect with the given ray and if yes, then add its content to the selection array
* @param ray defines the ray to test with
* @param selection defines the array to store current content if selection is positive
*/
OctreeBlock.prototype.intersectsRay = function (ray, selection) {
if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
if (this.blocks) {
for (var index = 0; index < this.blocks.length; index++) {
var block = this.blocks[index];
block.intersectsRay(ray, selection);
}
return;
}
selection.concatWithNoDuplicate(this.entries);
}
};
/**
* Subdivide the content into child blocks (this block will then be empty)
*/
OctreeBlock.prototype.createInnerBlocks = function () {
OctreeBlock._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
};
/**
* @hidden
*/
OctreeBlock._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
target.blocks = new Array();
var blockSize = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
// Segmenting space
for (var x = 0; x < 2; x++) {
for (var y = 0; y < 2; y++) {
for (var z = 0; z < 2; z++) {
var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
var block = new OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
block.addEntries(entries);
target.blocks.push(block);
}
}
}
};
return OctreeBlock;
}());
/***/ }),
/***/ "./Culling/Octrees/octreeSceneComponent.ts":
/*!*************************************************!*\
!*** ./Culling/Octrees/octreeSceneComponent.ts ***!
\*************************************************/
/*! exports provided: OctreeSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return OctreeSceneComponent; });
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../scene */ "./scene.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _octree__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./octree */ "./Culling/Octrees/octree.ts");
_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
if (maxCapacity === void 0) { maxCapacity = 64; }
if (maxDepth === void 0) { maxDepth = 2; }
var component = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE);
if (!component) {
component = new OctreeSceneComponent(this);
this._addComponent(component);
}
if (!this._selectionOctree) {
this._selectionOctree = new _octree__WEBPACK_IMPORTED_MODULE_5__["Octree"](_octree__WEBPACK_IMPORTED_MODULE_5__["Octree"].CreationFuncForMeshes, maxCapacity, maxDepth);
}
var worldExtends = this.getWorldExtends();
// Update octree
this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
return this._selectionOctree;
};
Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype, "selectionOctree", {
get: function () {
return this._selectionOctree;
},
enumerable: true,
configurable: true
});
/**
* This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
* Please note that you must have a decent number of submeshes to get performance improvements when using an octree
* @param maxCapacity defines the maximum size of each block (64 by default)
* @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
* @returns the new octree
* @see https://www.babylonjs-playground.com/#NA4OQ#12
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
*/
_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"].prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
if (maxCapacity === void 0) { maxCapacity = 64; }
if (maxDepth === void 0) { maxDepth = 2; }
var scene = this.getScene();
var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE);
if (!component) {
component = new OctreeSceneComponent(scene);
scene._addComponent(component);
}
if (!this._submeshesOctree) {
this._submeshesOctree = new _octree__WEBPACK_IMPORTED_MODULE_5__["Octree"](_octree__WEBPACK_IMPORTED_MODULE_5__["Octree"].CreationFuncForSubMeshes, maxCapacity, maxDepth);
}
this.computeWorldMatrix(true);
var boundingInfo = this.getBoundingInfo();
// Update octree
var bbox = boundingInfo.boundingBox;
this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
return this._submeshesOctree;
};
/**
* Defines the octree scene component responsible to manage any octrees
* in a given scene.
*/
var OctreeSceneComponent = /** @class */ (function () {
/**
* Creates a new instance of the component for the given scene
* @param scene Defines the scene to register the component in
*/
function OctreeSceneComponent(scene) {
/**
* The component name help to identify the component in the list of scene components.
*/
this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_4__["SceneComponentConstants"].NAME_OCTREE;
/**
* Indicates if the meshes have been checked to make sure they are isEnabled()
*/
this.checksIsEnabled = true;
this._tempRay = new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](1, 1, 1));
this.scene = scene;
this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
}
/**
* Registers the component in a given scene
*/
OctreeSceneComponent.prototype.register = function () {
var _this = this;
this.scene.onMeshRemovedObservable.add(function (mesh) {
var sceneOctree = _this.scene.selectionOctree;
if (sceneOctree !== undefined && sceneOctree !== null) {
var index = sceneOctree.dynamicContent.indexOf(mesh);
if (index !== -1) {
sceneOctree.dynamicContent.splice(index, 1);
}
}
});
this.scene.onMeshImportedObservable.add(function (mesh) {
var sceneOctree = _this.scene.selectionOctree;
if (sceneOctree !== undefined && sceneOctree !== null) {
sceneOctree.addMesh(mesh);
}
});
};
/**
* Return the list of active meshes
* @returns the list of active meshes
*/
OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
if (this.scene._selectionOctree) {
var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
return selection;
}
return this.scene._getDefaultMeshCandidates();
};
/**
* Return the list of active sub meshes
* @param mesh The mesh to get the candidates sub meshes from
* @returns the list of active sub meshes
*/
OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
return intersections;
}
return this.scene._getDefaultSubMeshCandidates(mesh);
};
/**
* Return the list of sub meshes intersecting with a given local ray
* @param mesh defines the mesh to find the submesh for
* @param localRay defines the ray in local space
* @returns the list of intersecting sub meshes
*/
OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
_Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"].TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
return intersections;
}
return this.scene._getDefaultSubMeshCandidates(mesh);
};
/**
* Return the list of sub meshes colliding with a collider
* @param mesh defines the mesh to find the submesh for
* @param collider defines the collider to evaluate the collision against
* @returns the list of colliding sub meshes
*/
OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
return intersections;
}
return this.scene._getDefaultSubMeshCandidates(mesh);
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
OctreeSceneComponent.prototype.rebuild = function () {
// Nothing to do here.
};
/**
* Disposes the component and the associated ressources.
*/
OctreeSceneComponent.prototype.dispose = function () {
// Nothing to do here.
};
return OctreeSceneComponent;
}());
/***/ }),
/***/ "./Culling/boundingBox.ts":
/*!********************************!*\
!*** ./Culling/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 _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.constants */ "./Maths/math.constants.ts");
/**
* Class used to store bounding box information
*/
var BoundingBox = /** @class */ (function () {
/**
* Creates a new bounding box
* @param min defines the minimum vector (in local space)
* @param max defines the maximum vector (in local space)
* @param worldMatrix defines the new world matrix
*/
function BoundingBox(min, max, worldMatrix) {
/**
* Gets the 8 vectors representing the bounding box in local space
*/
this.vectors = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(8, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
/**
* Gets the center of the bounding box in local space
*/
this.center = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the center of the bounding box in world space
*/
this.centerWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the extend size in local space
*/
this.extendSize = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the extend size in world space
*/
this.extendSizeWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the OBB (object bounding box) directions
*/
this.directions = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
/**
* Gets the 8 vectors representing the bounding box in world space
*/
this.vectorsWorld = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(8, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
/**
* Gets the minimum vector in world space
*/
this.minimumWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the maximum vector in world space
*/
this.maximumWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the minimum vector in local space
*/
this.minimum = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the maximum vector in local space
*/
this.maximum = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
this.reConstruct(min, max, worldMatrix);
}
// Methods
/**
* Recreates the entire bounding box from scratch as if we call the constructor in place
* @param min defines the new minimum vector (in local space)
* @param max defines the new maximum vector (in local space)
* @param worldMatrix defines the new world matrix
*/
BoundingBox.prototype.reConstruct = function (min, max, worldMatrix) {
var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
var vectors = this.vectors;
this.minimum.copyFromFloats(minX, minY, minZ);
this.maximum.copyFromFloats(maxX, maxY, maxZ);
vectors[0].copyFromFloats(minX, minY, minZ);
vectors[1].copyFromFloats(maxX, maxY, maxZ);
vectors[2].copyFromFloats(maxX, minY, minZ);
vectors[3].copyFromFloats(minX, maxY, minZ);
vectors[4].copyFromFloats(minX, minY, maxZ);
vectors[5].copyFromFloats(maxX, maxY, minZ);
vectors[6].copyFromFloats(minX, maxY, maxZ);
vectors[7].copyFromFloats(maxX, minY, maxZ);
// OBB
max.addToRef(min, this.center).scaleInPlace(0.5);
max.subtractToRef(min, this.extendSize).scaleInPlace(0.5);
this._worldMatrix = worldMatrix || _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly;
this._update(this._worldMatrix);
};
/**
* Scale the current bounding box by applying a scale factor
* @param factor defines the scale factor to apply
* @returns the current bounding box
*/
BoundingBox.prototype.scale = function (factor) {
var tmpVectors = BoundingBox.TmpVector3;
var diff = this.maximum.subtractToRef(this.minimum, tmpVectors[0]);
var len = diff.length();
diff.normalizeFromLength(len);
var distance = len * factor;
var newRadius = diff.scaleInPlace(distance * 0.5);
var min = this.center.subtractToRef(newRadius, tmpVectors[1]);
var max = this.center.addToRef(newRadius, tmpVectors[2]);
this.reConstruct(min, max, this._worldMatrix);
return this;
};
/**
* Gets the world matrix of the bounding box
* @returns a matrix
*/
BoundingBox.prototype.getWorldMatrix = function () {
return this._worldMatrix;
};
/** @hidden */
BoundingBox.prototype._update = function (world) {
var minWorld = this.minimumWorld;
var maxWorld = this.maximumWorld;
var directions = this.directions;
var vectorsWorld = this.vectorsWorld;
var vectors = this.vectors;
if (!world.isIdentity()) {
minWorld.setAll(Number.MAX_VALUE);
maxWorld.setAll(-Number.MAX_VALUE);
for (var index = 0; index < 8; ++index) {
var v = vectorsWorld[index];
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(vectors[index], world, v);
minWorld.minimizeInPlace(v);
maxWorld.maximizeInPlace(v);
}
// Extend
maxWorld.subtractToRef(minWorld, this.extendSizeWorld).scaleInPlace(0.5);
maxWorld.addToRef(minWorld, this.centerWorld).scaleInPlace(0.5);
}
else {
minWorld.copyFrom(this.minimum);
maxWorld.copyFrom(this.maximum);
for (var index = 0; index < 8; ++index) {
vectorsWorld[index].copyFrom(vectors[index]);
}
// Extend
this.extendSizeWorld.copyFrom(this.extendSize);
this.centerWorld.copyFrom(this.center);
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 0, directions[0]);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 4, directions[1]);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].FromArrayToRef(world.m, 8, directions[2]);
this._worldMatrix = world;
};
/**
* Tests if the bounding box is intersecting the frustum planes
* @param frustumPlanes defines the frustum planes to test
* @returns true if there is an intersection
*/
BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
};
/**
* Tests if the bounding box is entirely inside the frustum planes
* @param frustumPlanes defines the frustum planes to test
* @returns true if there is an inclusion
*/
BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
};
/**
* Tests if a point is inside the bounding box
* @param point defines the point to test
* @returns true if the point is inside the bounding box
*/
BoundingBox.prototype.intersectsPoint = function (point) {
var min = this.minimumWorld;
var max = this.maximumWorld;
var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
var pointX = point.x, pointY = point.y, pointZ = point.z;
var delta = -_Maths_math_constants__WEBPACK_IMPORTED_MODULE_2__["Epsilon"];
if (maxX - pointX < delta || delta > pointX - minX) {
return false;
}
if (maxY - pointY < delta || delta > pointY - minY) {
return false;
}
if (maxZ - pointZ < delta || delta > pointZ - minZ) {
return false;
}
return true;
};
/**
* Tests if the bounding box intersects with a bounding sphere
* @param sphere defines the sphere to test
* @returns true if there is an intersection
*/
BoundingBox.prototype.intersectsSphere = function (sphere) {
return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
};
/**
* Tests if the bounding box intersects with a box defined by a min and max vectors
* @param min defines the min vector to use
* @param max defines the max vector to use
* @returns true if there is an intersection
*/
BoundingBox.prototype.intersectsMinMax = function (min, max) {
var myMin = this.minimumWorld;
var myMax = this.maximumWorld;
var myMinX = myMin.x, myMinY = myMin.y, myMinZ = myMin.z, myMaxX = myMax.x, myMaxY = myMax.y, myMaxZ = myMax.z;
var minX = min.x, minY = min.y, minZ = min.z, maxX = max.x, maxY = max.y, maxZ = max.z;
if (myMaxX < minX || myMinX > maxX) {
return false;
}
if (myMaxY < minY || myMinY > maxY) {
return false;
}
if (myMaxZ < minZ || myMinZ > maxZ) {
return false;
}
return true;
};
// Statics
/**
* Tests if two bounding boxes are intersections
* @param box0 defines the first box to test
* @param box1 defines the second box to test
* @returns true if there is an intersection
*/
BoundingBox.Intersects = function (box0, box1) {
return box0.intersectsMinMax(box1.minimumWorld, box1.maximumWorld);
};
/**
* Tests if a bounding box defines by a min/max vectors intersects a sphere
* @param minPoint defines the minimum vector of the bounding box
* @param maxPoint defines the maximum vector of the bounding box
* @param sphereCenter defines the sphere center
* @param sphereRadius defines the sphere radius
* @returns true if there is an intersection
*/
BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
var vector = BoundingBox.TmpVector3[0];
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].ClampToRef(sphereCenter, minPoint, maxPoint, vector);
var num = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(sphereCenter, vector);
return (num <= (sphereRadius * sphereRadius));
};
/**
* Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
* @param boundingVectors defines an array of 8 vectors representing a bounding box
* @param frustumPlanes defines the frustum planes to test
* @return true if there is an inclusion
*/
BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
for (var p = 0; p < 6; ++p) {
var frustumPlane = frustumPlanes[p];
for (var i = 0; i < 8; ++i) {
if (frustumPlane.dotCoordinate(boundingVectors[i]) < 0) {
return false;
}
}
}
return true;
};
/**
* Tests if a bounding box defined with 8 vectors intersects frustum planes
* @param boundingVectors defines an array of 8 vectors representing a bounding box
* @param frustumPlanes defines the frustum planes to test
* @return true if there is an intersection
*/
BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
for (var p = 0; p < 6; ++p) {
var canReturnFalse = true;
var frustumPlane = frustumPlanes[p];
for (var i = 0; i < 8; ++i) {
if (frustumPlane.dotCoordinate(boundingVectors[i]) >= 0) {
canReturnFalse = false;
break;
}
}
if (canReturnFalse) {
return false;
}
}
return true;
};
BoundingBox.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
return BoundingBox;
}());
/***/ }),
/***/ "./Culling/boundingInfo.ts":
/*!*********************************!*\
!*** ./Culling/boundingInfo.ts ***!
\*********************************/
/*! exports provided: BoundingInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return BoundingInfo; });
/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _boundingBox__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./boundingBox */ "./Culling/boundingBox.ts");
/* harmony import */ var _boundingSphere__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./boundingSphere */ "./Culling/boundingSphere.ts");
var _result0 = { min: 0, max: 0 };
var _result1 = { min: 0, max: 0 };
var computeBoxExtents = function (axis, box, result) {
var p = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.centerWorld, axis);
var r0 = Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[0], axis)) * box.extendSize.x;
var r1 = Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[1], axis)) * box.extendSize.y;
var r2 = Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(box.directions[2], axis)) * box.extendSize.z;
var r = r0 + r1 + r2;
result.min = p - r;
result.max = p + r;
};
var axisOverlap = function (axis, box0, box1) {
computeBoxExtents(axis, box0, _result0);
computeBoxExtents(axis, box1, _result1);
return !(_result0.min > _result1.max || _result1.min > _result0.max);
};
/**
* Info for a bounding data of a mesh
*/
var BoundingInfo = /** @class */ (function () {
/**
* Constructs bounding info
* @param minimum min vector of the bounding box/sphere
* @param maximum max vector of the bounding box/sphere
* @param worldMatrix defines the new world matrix
*/
function BoundingInfo(minimum, maximum, worldMatrix) {
this._isLocked = false;
this.boundingBox = new _boundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"](minimum, maximum, worldMatrix);
this.boundingSphere = new _boundingSphere__WEBPACK_IMPORTED_MODULE_4__["BoundingSphere"](minimum, maximum, worldMatrix);
}
/**
* Recreates the entire bounding info from scratch as if we call the constructor in place
* @param min defines the new minimum vector (in local space)
* @param max defines the new maximum vector (in local space)
* @param worldMatrix defines the new world matrix
*/
BoundingInfo.prototype.reConstruct = function (min, max, worldMatrix) {
this.boundingBox.reConstruct(min, max, worldMatrix);
this.boundingSphere.reConstruct(min, max, worldMatrix);
};
Object.defineProperty(BoundingInfo.prototype, "minimum", {
/**
* min vector of the bounding box/sphere
*/
get: function () {
return this.boundingBox.minimum;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BoundingInfo.prototype, "maximum", {
/**
* max vector of the bounding box/sphere
*/
get: function () {
return this.boundingBox.maximum;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BoundingInfo.prototype, "isLocked", {
/**
* If the info is locked and won't be updated to avoid perf overhead
*/
get: function () {
return this._isLocked;
},
set: function (value) {
this._isLocked = value;
},
enumerable: false,
configurable: true
});
// Methods
/**
* Updates the bounding sphere and box
* @param world world matrix to be used to update
*/
BoundingInfo.prototype.update = function (world) {
if (this._isLocked) {
return;
}
this.boundingBox._update(world);
this.boundingSphere._update(world);
};
/**
* Recreate the bounding info to be centered around a specific point given a specific extend.
* @param center New center of the bounding info
* @param extend New extend of the bounding info
* @returns the current bounding info
*/
BoundingInfo.prototype.centerOn = function (center, extend) {
var minimum = BoundingInfo.TmpVector3[0].copyFrom(center).subtractInPlace(extend);
var maximum = BoundingInfo.TmpVector3[1].copyFrom(center).addInPlace(extend);
this.boundingBox.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
this.boundingSphere.reConstruct(minimum, maximum, this.boundingBox.getWorldMatrix());
return this;
};
/**
* Scale the current bounding info by applying a scale factor
* @param factor defines the scale factor to apply
* @returns the current bounding info
*/
BoundingInfo.prototype.scale = function (factor) {
this.boundingBox.scale(factor);
this.boundingSphere.scale(factor);
return this;
};
/**
* Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
* @param frustumPlanes defines the frustum to test
* @param strategy defines the strategy to use for the culling (default is BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD)
* @returns true if the bounding info is in the frustum planes
*/
BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
if (strategy === void 0) { strategy = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_STANDARD; }
var inclusionTest = (strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION || strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY);
if (inclusionTest) {
if (this.boundingSphere.isCenterInFrustum(frustumPlanes)) {
return true;
}
}
if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
return false;
}
var bSphereOnlyTest = (strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY || strategy === _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY);
if (bSphereOnlyTest) {
return true;
}
return this.boundingBox.isInFrustum(frustumPlanes);
};
Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
/**
* Gets the world distance between the min and max points of the bounding box
*/
get: function () {
var boundingBox = this.boundingBox;
var diag = boundingBox.maximumWorld.subtractToRef(boundingBox.minimumWorld, BoundingInfo.TmpVector3[0]);
return diag.length();
},
enumerable: false,
configurable: true
});
/**
* Checks if a cullable object (mesh...) is in the camera frustum
* Unlike isInFrustum this cheks the full bounding box
* @param frustumPlanes Camera near/planes
* @returns true if the object is in frustum otherwise false
*/
BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
};
/** @hidden */
BoundingInfo.prototype._checkCollision = function (collider) {
return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
};
/**
* Checks if a point is inside the bounding box and bounding sphere or the mesh
* @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
* @param point the point to check intersection with
* @returns if the point intersects
*/
BoundingInfo.prototype.intersectsPoint = function (point) {
if (!this.boundingSphere.centerWorld) {
return false;
}
if (!this.boundingSphere.intersectsPoint(point)) {
return false;
}
if (!this.boundingBox.intersectsPoint(point)) {
return false;
}
return true;
};
/**
* Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
* @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
* @param boundingInfo the bounding info to check intersection with
* @param precise if the intersection should be done using OBB
* @returns if the bounding info intersects
*/
BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
if (!_boundingSphere__WEBPACK_IMPORTED_MODULE_4__["BoundingSphere"].Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
return false;
}
if (!_boundingBox__WEBPACK_IMPORTED_MODULE_3__["BoundingBox"].Intersects(this.boundingBox, boundingInfo.boundingBox)) {
return false;
}
if (!precise) {
return true;
}
var box0 = this.boundingBox;
var box1 = boundingInfo.boundingBox;
if (!axisOverlap(box0.directions[0], box0, box1)) {
return false;
}
if (!axisOverlap(box0.directions[1], box0, box1)) {
return false;
}
if (!axisOverlap(box0.directions[2], box0, box1)) {
return false;
}
if (!axisOverlap(box1.directions[0], box0, box1)) {
return false;
}
if (!axisOverlap(box1.directions[1], box0, box1)) {
return false;
}
if (!axisOverlap(box1.directions[2], box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[0]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[1]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[0], box1.directions[2]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[0]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[1]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[1], box1.directions[2]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[0]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[1]), box0, box1)) {
return false;
}
if (!axisOverlap(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Cross(box0.directions[2], box1.directions[2]), box0, box1)) {
return false;
}
return true;
};
BoundingInfo.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(2, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
return BoundingInfo;
}());
/***/ }),
/***/ "./Culling/boundingSphere.ts":
/*!***********************************!*\
!*** ./Culling/boundingSphere.ts ***!
\***********************************/
/*! exports provided: BoundingSphere */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return BoundingSphere; });
/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/**
* Class used to store bounding sphere information
*/
var BoundingSphere = /** @class */ (function () {
/**
* Creates a new bounding sphere
* @param min defines the minimum vector (in local space)
* @param max defines the maximum vector (in local space)
* @param worldMatrix defines the new world matrix
*/
function BoundingSphere(min, max, worldMatrix) {
/**
* Gets the center of the bounding sphere in local space
*/
this.center = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the center of the bounding sphere in world space
*/
this.centerWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the minimum vector in local space
*/
this.minimum = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
/**
* Gets the maximum vector in local space
*/
this.maximum = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
this.reConstruct(min, max, worldMatrix);
}
/**
* Recreates the entire bounding sphere from scratch as if we call the constructor in place
* @param min defines the new minimum vector (in local space)
* @param max defines the new maximum vector (in local space)
* @param worldMatrix defines the new world matrix
*/
BoundingSphere.prototype.reConstruct = function (min, max, worldMatrix) {
this.minimum.copyFrom(min);
this.maximum.copyFrom(max);
var distance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Distance(min, max);
max.addToRef(min, this.center).scaleInPlace(0.5);
this.radius = distance * 0.5;
this._update(worldMatrix || _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly);
};
/**
* Scale the current bounding sphere by applying a scale factor
* @param factor defines the scale factor to apply
* @returns the current bounding box
*/
BoundingSphere.prototype.scale = function (factor) {
var newRadius = this.radius * factor;
var tmpVectors = BoundingSphere.TmpVector3;
var tempRadiusVector = tmpVectors[0].setAll(newRadius);
var min = this.center.subtractToRef(tempRadiusVector, tmpVectors[1]);
var max = this.center.addToRef(tempRadiusVector, tmpVectors[2]);
this.reConstruct(min, max, this._worldMatrix);
return this;
};
/**
* Gets the world matrix of the bounding box
* @returns a matrix
*/
BoundingSphere.prototype.getWorldMatrix = function () {
return this._worldMatrix;
};
// Methods
/** @hidden */
BoundingSphere.prototype._update = function (worldMatrix) {
if (!worldMatrix.isIdentity()) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(this.center, worldMatrix, this.centerWorld);
var tempVector = BoundingSphere.TmpVector3[0];
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, worldMatrix, tempVector);
this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
}
else {
this.centerWorld.copyFrom(this.center);
this.radiusWorld = this.radius;
}
};
/**
* Tests if the bounding sphere is intersecting the frustum planes
* @param frustumPlanes defines the frustum planes to test
* @returns true if there is an intersection
*/
BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
var center = this.centerWorld;
var radius = this.radiusWorld;
for (var i = 0; i < 6; i++) {
if (frustumPlanes[i].dotCoordinate(center) <= -radius) {
return false;
}
}
return true;
};
/**
* Tests if the bounding sphere center is in between the frustum planes.
* Used for optimistic fast inclusion.
* @param frustumPlanes defines the frustum planes to test
* @returns true if the sphere center is in between the frustum planes
*/
BoundingSphere.prototype.isCenterInFrustum = function (frustumPlanes) {
var center = this.centerWorld;
for (var i = 0; i < 6; i++) {
if (frustumPlanes[i].dotCoordinate(center) < 0) {
return false;
}
}
return true;
};
/**
* Tests if a point is inside the bounding sphere
* @param point defines the point to test
* @returns true if the point is inside the bounding sphere
*/
BoundingSphere.prototype.intersectsPoint = function (point) {
var squareDistance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.centerWorld, point);
if (this.radiusWorld * this.radiusWorld < squareDistance) {
return false;
}
return true;
};
// Statics
/**
* Checks if two sphere intersct
* @param sphere0 sphere 0
* @param sphere1 sphere 1
* @returns true if the speres intersect
*/
BoundingSphere.Intersects = function (sphere0, sphere1) {
var squareDistance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(sphere0.centerWorld, sphere1.centerWorld);
var radiusSum = sphere0.radiusWorld + sphere1.radiusWorld;
if (radiusSum * radiusSum < squareDistance) {
return false;
}
return true;
};
BoundingSphere.TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(3, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
return BoundingSphere;
}());
/***/ }),
/***/ "./Culling/index.ts":
/*!**************************!*\
!*** ./Culling/index.ts ***!
\**************************/
/*! exports provided: BoundingBox, BoundingInfo, BoundingSphere, Octree, OctreeBlock, OctreeSceneComponent, Ray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _boundingBox__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./boundingBox */ "./Culling/boundingBox.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _boundingBox__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"]; });
/* harmony import */ var _boundingInfo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boundingInfo */ "./Culling/boundingInfo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return _boundingInfo__WEBPACK_IMPORTED_MODULE_1__["BoundingInfo"]; });
/* harmony import */ var _boundingSphere__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boundingSphere */ "./Culling/boundingSphere.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return _boundingSphere__WEBPACK_IMPORTED_MODULE_2__["BoundingSphere"]; });
/* harmony import */ var _Octrees_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Octrees/index */ "./Culling/Octrees/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["Octree"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["OctreeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _Octrees_index__WEBPACK_IMPORTED_MODULE_3__["OctreeSceneComponent"]; });
/* harmony import */ var _ray__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./ray */ "./Culling/ray.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return _ray__WEBPACK_IMPORTED_MODULE_4__["Ray"]; });
/***/ }),
/***/ "./Culling/ray.ts":
/*!************************!*\
!*** ./Culling/ray.ts ***!
\************************/
/*! exports provided: Ray */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return Ray; });
/* harmony import */ var _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/arrayTools */ "./Misc/arrayTools.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Collisions/pickingInfo */ "./Collisions/pickingInfo.ts");
/* harmony import */ var _Collisions_intersectionInfo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Collisions/intersectionInfo */ "./Collisions/intersectionInfo.ts");
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../scene */ "./scene.ts");
/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Cameras/camera */ "./Cameras/camera.ts");
/**
* Class representing a ray with position and direction
*/
var Ray = /** @class */ (function () {
/**
* Creates a new ray
* @param origin origin point
* @param direction direction
* @param length length of the ray
*/
function Ray(
/** origin point */
origin,
/** direction */
direction,
/** length of the ray */
length) {
if (length === void 0) { length = Number.MAX_VALUE; }
this.origin = origin;
this.direction = direction;
this.length = length;
}
// Methods
/**
* Checks if the ray intersects a box
* This does not account for the ray lenght by design to improve perfs.
* @param minimum bound of the box
* @param maximum bound of the box
* @param intersectionTreshold extra extend to be added to the box in all direction
* @returns if the box was hit
*/
Ray.prototype.intersectsBoxMinMax = function (minimum, maximum, intersectionTreshold) {
if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
var newMinimum = Ray._TmpVector3[0].copyFromFloats(minimum.x - intersectionTreshold, minimum.y - intersectionTreshold, minimum.z - intersectionTreshold);
var newMaximum = Ray._TmpVector3[1].copyFromFloats(maximum.x + intersectionTreshold, maximum.y + intersectionTreshold, maximum.z + intersectionTreshold);
var d = 0.0;
var maxValue = Number.MAX_VALUE;
var inv;
var min;
var max;
var temp;
if (Math.abs(this.direction.x) < 0.0000001) {
if (this.origin.x < newMinimum.x || this.origin.x > newMaximum.x) {
return false;
}
}
else {
inv = 1.0 / this.direction.x;
min = (newMinimum.x - this.origin.x) * inv;
max = (newMaximum.x - this.origin.x) * inv;
if (max === -Infinity) {
max = Infinity;
}
if (min > max) {
temp = min;
min = max;
max = temp;
}
d = Math.max(min, d);
maxValue = Math.min(max, maxValue);
if (d > maxValue) {
return false;
}
}
if (Math.abs(this.direction.y) < 0.0000001) {
if (this.origin.y < newMinimum.y || this.origin.y > newMaximum.y) {
return false;
}
}
else {
inv = 1.0 / this.direction.y;
min = (newMinimum.y - this.origin.y) * inv;
max = (newMaximum.y - this.origin.y) * inv;
if (max === -Infinity) {
max = Infinity;
}
if (min > max) {
temp = min;
min = max;
max = temp;
}
d = Math.max(min, d);
maxValue = Math.min(max, maxValue);
if (d > maxValue) {
return false;
}
}
if (Math.abs(this.direction.z) < 0.0000001) {
if (this.origin.z < newMinimum.z || this.origin.z > newMaximum.z) {
return false;
}
}
else {
inv = 1.0 / this.direction.z;
min = (newMinimum.z - this.origin.z) * inv;
max = (newMaximum.z - this.origin.z) * inv;
if (max === -Infinity) {
max = Infinity;
}
if (min > max) {
temp = min;
min = max;
max = temp;
}
d = Math.max(min, d);
maxValue = Math.min(max, maxValue);
if (d > maxValue) {
return false;
}
}
return true;
};
/**
* Checks if the ray intersects a box
* This does not account for the ray lenght by design to improve perfs.
* @param box the bounding box to check
* @param intersectionTreshold extra extend to be added to the BoundingBox in all direction
* @returns if the box was hit
*/
Ray.prototype.intersectsBox = function (box, intersectionTreshold) {
if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
return this.intersectsBoxMinMax(box.minimum, box.maximum, intersectionTreshold);
};
/**
* If the ray hits a sphere
* @param sphere the bounding sphere to check
* @param intersectionTreshold extra extend to be added to the BoundingSphere in all direction
* @returns true if it hits the sphere
*/
Ray.prototype.intersectsSphere = function (sphere, intersectionTreshold) {
if (intersectionTreshold === void 0) { intersectionTreshold = 0; }
var x = sphere.center.x - this.origin.x;
var y = sphere.center.y - this.origin.y;
var z = sphere.center.z - this.origin.z;
var pyth = x * x + y * y + z * z;
var radius = sphere.radius + intersectionTreshold;
var rr = radius * radius;
if (pyth <= rr) {
return true;
}
var dot = x * this.direction.x + y * this.direction.y + z * this.direction.z;
if (dot < 0.0) {
return false;
}
var temp = pyth - dot * dot;
return temp <= rr;
};
/**
* If the ray hits a triange
* @param vertex0 triangle vertex
* @param vertex1 triangle vertex
* @param vertex2 triangle vertex
* @returns intersection information if hit
*/
Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
var edge1 = Ray._TmpVector3[0];
var edge2 = Ray._TmpVector3[1];
var pvec = Ray._TmpVector3[2];
var tvec = Ray._TmpVector3[3];
var qvec = Ray._TmpVector3[4];
vertex1.subtractToRef(vertex0, edge1);
vertex2.subtractToRef(vertex0, edge2);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(this.direction, edge2, pvec);
var det = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(edge1, pvec);
if (det === 0) {
return null;
}
var invdet = 1 / det;
this.origin.subtractToRef(vertex0, tvec);
var bv = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(tvec, pvec) * invdet;
if (bv < 0 || bv > 1.0) {
return null;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].CrossToRef(tvec, edge1, qvec);
var bw = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this.direction, qvec) * invdet;
if (bw < 0 || bv + bw > 1.0) {
return null;
}
//check if the distance is longer than the predefined length.
var distance = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(edge2, qvec) * invdet;
if (distance > this.length) {
return null;
}
return new _Collisions_intersectionInfo__WEBPACK_IMPORTED_MODULE_3__["IntersectionInfo"](1 - bv - bw, bv, distance);
};
/**
* Checks if ray intersects a plane
* @param plane the plane to check
* @returns the distance away it was hit
*/
Ray.prototype.intersectsPlane = function (plane) {
var distance;
var result1 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(plane.normal, this.direction);
if (Math.abs(result1) < 9.99999997475243e-7) {
return null;
}
else {
var result2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(plane.normal, this.origin);
distance = (-plane.d - result2) / result1;
if (distance < 0.0) {
if (distance < -9.99999997475243e-7) {
return null;
}
else {
return 0;
}
}
return distance;
}
};
/**
* Calculate the intercept of a ray on a given axis
* @param axis to check 'x' | 'y' | 'z'
* @param offset from axis interception (i.e. an offset of 1y is intercepted above ground)
* @returns a vector containing the coordinates where 'axis' is equal to zero (else offset), or null if there is no intercept.
*/
Ray.prototype.intersectsAxis = function (axis, offset) {
if (offset === void 0) { offset = 0; }
switch (axis) {
case "y":
var t = (this.origin.y - offset) / this.direction.y;
if (t > 0) {
return null;
}
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](this.origin.x + this.direction.x * -t, offset, this.origin.z + this.direction.z * -t);
case "x":
var t = (this.origin.x - offset) / this.direction.x;
if (t > 0) {
return null;
}
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](offset, this.origin.y + this.direction.y * -t, this.origin.z + this.direction.z * -t);
case "z":
var t = (this.origin.z - offset) / this.direction.z;
if (t > 0) {
return null;
}
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](this.origin.x + this.direction.x * -t, this.origin.y + this.direction.y * -t, offset);
default:
return null;
}
};
/**
* Checks if ray intersects a mesh
* @param mesh the mesh to check
* @param fastCheck defines if the first intersection will be used (and not the closest)
* @returns picking info of the intersecton
*/
Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
var tm = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Matrix[0];
mesh.getWorldMatrix().invertToRef(tm);
if (this._tmpRay) {
Ray.TransformToRef(this, tm, this._tmpRay);
}
else {
this._tmpRay = Ray.Transform(this, tm);
}
return mesh.intersects(this._tmpRay, fastCheck);
};
/**
* Checks if ray intersects a mesh
* @param meshes the meshes to check
* @param fastCheck defines if the first intersection will be used (and not the closest)
* @param results array to store result in
* @returns Array of picking infos
*/
Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
if (results) {
results.length = 0;
}
else {
results = [];
}
for (var i = 0; i < meshes.length; i++) {
var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
if (pickInfo.hit) {
results.push(pickInfo);
}
}
results.sort(this._comparePickingInfo);
return results;
};
Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
if (pickingInfoA.distance < pickingInfoB.distance) {
return -1;
}
else if (pickingInfoA.distance > pickingInfoB.distance) {
return 1;
}
else {
return 0;
}
};
/**
* Intersection test between the ray and a given segment whithin a given tolerance (threshold)
* @param sega the first point of the segment to test the intersection against
* @param segb the second point of the segment to test the intersection against
* @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
* @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
*/
Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
var o = this.origin;
var u = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[0];
var rsegb = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[1];
var v = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[2];
var w = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[3];
segb.subtractToRef(sega, u);
this.direction.scaleToRef(Ray.rayl, v);
o.addToRef(v, rsegb);
sega.subtractToRef(o, w);
var a = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, u); // always >= 0
var b = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, v);
var c = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(v, v); // always >= 0
var d = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(u, w);
var e = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(v, w);
var D = a * c - b * b; // always >= 0
var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
// compute the line parameters of the two closest points
if (D < Ray.smallnum) {
// the lines are almost parallel
sN = 0.0; // force using point P0 on segment S1
sD = 1.0; // to prevent possible division by 0.0 later
tN = e;
tD = c;
}
else {
// get the closest points on the infinite lines
sN = b * e - c * d;
tN = a * e - b * d;
if (sN < 0.0) {
// sc < 0 => the s=0 edge is visible
sN = 0.0;
tN = e;
tD = c;
}
else if (sN > sD) {
// sc > 1 => the s=1 edge is visible
sN = sD;
tN = e + b;
tD = c;
}
}
if (tN < 0.0) {
// tc < 0 => the t=0 edge is visible
tN = 0.0;
// recompute sc for this edge
if (-d < 0.0) {
sN = 0.0;
}
else if (-d > a) {
sN = sD;
}
else {
sN = -d;
sD = a;
}
}
else if (tN > tD) {
// tc > 1 => the t=1 edge is visible
tN = tD;
// recompute sc for this edge
if (-d + b < 0.0) {
sN = 0;
}
else if (-d + b > a) {
sN = sD;
}
else {
sN = -d + b;
sD = a;
}
}
// finally do the division to get sc and tc
sc = Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD;
tc = Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD;
// get the difference of the two closest points
var qtc = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[4];
v.scaleToRef(tc, qtc);
var qsc = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[5];
u.scaleToRef(sc, qsc);
qsc.addInPlace(w);
var dP = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[6];
qsc.subtractToRef(qtc, dP); // = S1(sc) - S2(tc)
var isIntersected = tc > 0 && tc <= this.length && dP.lengthSquared() < threshold * threshold; // return intersection result
if (isIntersected) {
return qsc.length();
}
return -1;
};
/**
* Update the ray from viewport position
* @param x position
* @param y y position
* @param viewportWidth viewport width
* @param viewportHeight viewport height
* @param world world matrix
* @param view view matrix
* @param projection projection matrix
* @returns this ray updated
*/
Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
this.unprojectRayToRef(x, y, viewportWidth, viewportHeight, world, view, projection);
return this;
};
// Statics
/**
* Creates a ray with origin and direction of 0,0,0
* @returns the new ray
*/
Ray.Zero = function () {
return new Ray(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero());
};
/**
* Creates a new ray from screen space and viewport
* @param x position
* @param y y position
* @param viewportWidth viewport width
* @param viewportHeight viewport height
* @param world world matrix
* @param view view matrix
* @param projection projection matrix
* @returns new ray
*/
Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
var result = Ray.Zero();
return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
};
/**
* Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
* transformed to the given world matrix.
* @param origin The origin point
* @param end The end point
* @param world a matrix to transform the ray to. Default is the identity matrix.
* @returns the new ray
*/
Ray.CreateNewFromTo = function (origin, end, world) {
if (world === void 0) { world = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly; }
var direction = end.subtract(origin);
var length = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z);
direction.normalize();
return Ray.Transform(new Ray(origin, direction, length), world);
};
/**
* Transforms a ray by a matrix
* @param ray ray to transform
* @param matrix matrix to apply
* @returns the resulting new ray
*/
Ray.Transform = function (ray, matrix) {
var result = new Ray(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0));
Ray.TransformToRef(ray, matrix, result);
return result;
};
/**
* Transforms a ray by a matrix
* @param ray ray to transform
* @param matrix matrix to apply
* @param result ray to store result in
*/
Ray.TransformToRef = function (ray, matrix, result) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(ray.origin, matrix, result.origin);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(ray.direction, matrix, result.direction);
result.length = ray.length;
var dir = result.direction;
var len = dir.length();
if (!(len === 0 || len === 1)) {
var num = 1.0 / len;
dir.x *= num;
dir.y *= num;
dir.z *= num;
result.length *= len;
}
};
/**
* Unproject a ray from screen space to object space
* @param sourceX defines the screen space x coordinate to use
* @param sourceY defines the screen space y coordinate to use
* @param viewportWidth defines the current width of the viewport
* @param viewportHeight defines the current height of the viewport
* @param world defines the world matrix to use (can be set to Identity to go to world space)
* @param view defines the view matrix to use
* @param projection defines the projection matrix to use
*/
Ray.prototype.unprojectRayToRef = function (sourceX, sourceY, viewportWidth, viewportHeight, world, view, projection) {
var matrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Matrix[0];
world.multiplyToRef(view, matrix);
matrix.multiplyToRef(projection, matrix);
matrix.invert();
var nearScreenSource = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[0];
nearScreenSource.x = (sourceX / viewportWidth) * 2 - 1;
nearScreenSource.y = -((sourceY / viewportHeight) * 2 - 1);
nearScreenSource.z = -1.0;
var farScreenSource = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[1].copyFromFloats(nearScreenSource.x, nearScreenSource.y, 1.0);
var nearVec3 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[2];
var farVec3 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[3];
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]._UnprojectFromInvertedMatrixToRef(nearScreenSource, matrix, nearVec3);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]._UnprojectFromInvertedMatrixToRef(farScreenSource, matrix, farVec3);
this.origin.copyFrom(nearVec3);
farVec3.subtractToRef(nearVec3, this.direction);
this.direction.normalize();
};
Ray._TmpVector3 = _Misc_arrayTools__WEBPACK_IMPORTED_MODULE_0__["ArrayTools"].BuildArray(6, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero);
Ray.smallnum = 0.00000001;
Ray.rayl = 10e8;
return Ray;
}());
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
if (cameraViewSpace === void 0) { cameraViewSpace = false; }
var result = Ray.Zero();
this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
return result;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
if (cameraViewSpace === void 0) { cameraViewSpace = false; }
var engine = this.getEngine();
if (!camera) {
if (!this.activeCamera) {
return this;
}
camera = this.activeCamera;
}
var cameraViewport = camera.viewport;
var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
// Moving coordinates to local viewport world
x = x / engine.getHardwareScalingLevel() - viewport.x;
y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height);
result.update(x, y, viewport.width, viewport.height, world ? world : _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly, cameraViewSpace ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].IdentityReadOnly : camera.getViewMatrix(), camera.getProjectionMatrix());
return this;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayInCameraSpace = function (x, y, camera) {
var result = Ray.Zero();
this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
return result;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) {
return this;
}
var engine = this.getEngine();
if (!camera) {
if (!this.activeCamera) {
throw new Error("Active camera not set");
}
camera = this.activeCamera;
}
var cameraViewport = camera.viewport;
var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
var identity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity();
// Moving coordinates to local viewport world
x = x / engine.getHardwareScalingLevel() - viewport.x;
y = y / engine.getHardwareScalingLevel() - (engine.getRenderHeight() - viewport.y - viewport.height);
result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
return this;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalPickForMesh = function (pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate) {
var ray = rayFunction(world);
var result = mesh.intersects(ray, fastCheck, trianglePredicate, onlyBoundingInfo, world);
if (!result || !result.hit) {
return null;
}
if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance) {
return null;
}
return result;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalPick = function (rayFunction, predicate, fastCheck, onlyBoundingInfo, trianglePredicate) {
if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) {
return null;
}
var pickingInfo = null;
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh = this.meshes[meshIndex];
if (predicate) {
if (!predicate(mesh)) {
continue;
}
}
else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
continue;
}
var world = mesh.skeleton && mesh.skeleton.overrideMesh ? mesh.skeleton.overrideMesh.getWorldMatrix() : mesh.getWorldMatrix();
if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {
var tmpMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Matrix[0];
var thinMatrices = mesh.thinInstanceGetWorldMatrices();
for (var index = 0; index < thinMatrices.length; index++) {
var thinMatrix = thinMatrices[index];
thinMatrix.multiplyToRef(world, tmpMatrix);
var result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, tmpMatrix, fastCheck, onlyBoundingInfo, trianglePredicate);
if (result) {
pickingInfo = result;
pickingInfo.thinInstanceIndex = index;
if (fastCheck) {
return pickingInfo;
}
}
}
}
else {
var result = this._internalPickForMesh(pickingInfo, rayFunction, mesh, world, fastCheck, onlyBoundingInfo, trianglePredicate);
if (result) {
pickingInfo = result;
if (fastCheck) {
return pickingInfo;
}
}
}
}
return pickingInfo || new _Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]();
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype._internalMultiPick = function (rayFunction, predicate, trianglePredicate) {
if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) {
return null;
}
var pickingInfos = new Array();
for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
var mesh = this.meshes[meshIndex];
if (predicate) {
if (!predicate(mesh)) {
continue;
}
}
else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
continue;
}
var world = mesh.skeleton && mesh.skeleton.overrideMesh ? mesh.skeleton.overrideMesh.getWorldMatrix() : mesh.getWorldMatrix();
if (mesh.hasThinInstances && mesh.thinInstanceEnablePicking) {
var tmpMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Matrix[0];
var thinMatrices = mesh.thinInstanceGetWorldMatrices();
for (var index = 0; index < thinMatrices.length; index++) {
var thinMatrix = thinMatrices[index];
thinMatrix.multiplyToRef(world, tmpMatrix);
var result = this._internalPickForMesh(null, rayFunction, mesh, tmpMatrix, false, false, trianglePredicate);
if (result) {
result.thinInstanceIndex = index;
pickingInfos.push(result);
}
}
}
else {
var result = this._internalPickForMesh(null, rayFunction, mesh, world, false, false, trianglePredicate);
if (result) {
pickingInfos.push(result);
}
}
}
return pickingInfos;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pickWithBoundingInfo = function (x, y, predicate, fastCheck, camera) {
var _this = this;
if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) {
return null;
}
var result = this._internalPick(function (world) {
if (!_this._tempPickingRay) {
_this._tempPickingRay = Ray.Zero();
}
_this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
return _this._tempPickingRay;
}, predicate, fastCheck, true);
if (result) {
result.ray = this.createPickingRay(x, y, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), camera || null);
}
return result;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pick = function (x, y, predicate, fastCheck, camera, trianglePredicate) {
var _this = this;
if (!_Collisions_pickingInfo__WEBPACK_IMPORTED_MODULE_2__["PickingInfo"]) {
return null;
}
var result = this._internalPick(function (world) {
if (!_this._tempPickingRay) {
_this._tempPickingRay = Ray.Zero();
}
_this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
return _this._tempPickingRay;
}, predicate, fastCheck, false, trianglePredicate);
if (result) {
result.ray = this.createPickingRay(x, y, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), camera || null);
}
return result;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.pickWithRay = function (ray, predicate, fastCheck, trianglePredicate) {
var _this = this;
var result = this._internalPick(function (world) {
if (!_this._pickWithRayInverseMatrix) {
_this._pickWithRayInverseMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity();
}
world.invertToRef(_this._pickWithRayInverseMatrix);
if (!_this._cachedRayForTransform) {
_this._cachedRayForTransform = Ray.Zero();
}
Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
return _this._cachedRayForTransform;
}, predicate, fastCheck, false, trianglePredicate);
if (result) {
result.ray = ray;
}
return result;
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.multiPick = function (x, y, predicate, camera, trianglePredicate) {
var _this = this;
return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate, trianglePredicate);
};
_scene__WEBPACK_IMPORTED_MODULE_4__["Scene"].prototype.multiPickWithRay = function (ray, predicate, trianglePredicate) {
var _this = this;
return this._internalMultiPick(function (world) {
if (!_this._pickWithRayInverseMatrix) {
_this._pickWithRayInverseMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity();
}
world.invertToRef(_this._pickWithRayInverseMatrix);
if (!_this._cachedRayForTransform) {
_this._cachedRayForTransform = Ray.Zero();
}
Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
return _this._cachedRayForTransform;
}, predicate, trianglePredicate);
};
_Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].prototype.getForwardRay = function (length, transform, origin) {
if (length === void 0) { length = 100; }
return this.getForwardRayToRef(new Ray(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero(), length), length, transform, origin);
};
_Cameras_camera__WEBPACK_IMPORTED_MODULE_5__["Camera"].prototype.getForwardRayToRef = function (refRay, length, transform, origin) {
if (length === void 0) { length = 100; }
if (!transform) {
transform = this.getWorldMatrix();
}
refRay.length = length;
if (!origin) {
refRay.origin.copyFrom(this.position);
}
else {
refRay.origin.copyFrom(origin);
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[2].set(0, 0, this._scene.useRightHandedSystem ? -1 : 1);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformNormalToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[2], transform, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[3]);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].NormalizeToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["TmpVectors"].Vector3[3], refRay.direction);
return refRay;
};
/***/ }),
/***/ "./Debug/ISkeletonViewer.ts":
/*!**********************************!*\
!*** ./Debug/ISkeletonViewer.ts ***!
\**********************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Debug/axesViewer.ts":
/*!*****************************!*\
!*** ./Debug/axesViewer.ts ***!
\*****************************/
/*! exports provided: AxesViewer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return AxesViewer; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gizmos/axisDragGizmo */ "./Gizmos/axisDragGizmo.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/**
* The Axes viewer will show 3 axes in a specific point in space
*/
var AxesViewer = /** @class */ (function () {
/**
* Creates a new AxesViewer
* @param scene defines the hosting scene
* @param scaleLines defines a number used to scale line length (1 by default)
* @param renderingGroupId defines a number used to set the renderingGroupId of the meshes (2 by default)
* @param xAxis defines the node hierarchy used to render the x-axis
* @param yAxis defines the node hierarchy used to render the y-axis
* @param zAxis defines the node hierarchy used to render the z-axis
*/
function AxesViewer(scene, scaleLines, renderingGroupId, xAxis, yAxis, zAxis) {
if (scaleLines === void 0) { scaleLines = 1; }
if (renderingGroupId === void 0) { renderingGroupId = 2; }
this._scaleLinesFactor = 4;
this._instanced = false;
/**
* Gets the hosting scene
*/
this.scene = null;
/**
* Gets or sets a number used to scale line length
*/
this.scaleLines = 1;
this.scaleLines = scaleLines;
if (!xAxis) {
var redColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene);
redColoredMaterial.disableLighting = true;
redColoredMaterial.emissiveColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].Red().scale(0.5);
xAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, redColoredMaterial);
}
if (!yAxis) {
var greenColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene);
greenColoredMaterial.disableLighting = true;
greenColoredMaterial.emissiveColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].Green().scale(0.5);
yAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, greenColoredMaterial);
}
if (!zAxis) {
var blueColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_1__["StandardMaterial"]("", scene);
blueColoredMaterial.disableLighting = true;
blueColoredMaterial.emissiveColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].Blue().scale(0.5);
zAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrow(scene, blueColoredMaterial);
}
this._xAxis = xAxis;
this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
this._yAxis = yAxis;
this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
this._zAxis = zAxis;
this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
if (renderingGroupId != null) {
AxesViewer._SetRenderingGroupId(this._xAxis, renderingGroupId);
AxesViewer._SetRenderingGroupId(this._yAxis, renderingGroupId);
AxesViewer._SetRenderingGroupId(this._zAxis, renderingGroupId);
}
this.scene = scene;
this.update(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Right(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Forward());
}
Object.defineProperty(AxesViewer.prototype, "xAxis", {
/** Gets the node hierarchy used to render x-axis */
get: function () {
return this._xAxis;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AxesViewer.prototype, "yAxis", {
/** Gets the node hierarchy used to render y-axis */
get: function () {
return this._yAxis;
},
enumerable: false,
configurable: true
});
Object.defineProperty(AxesViewer.prototype, "zAxis", {
/** Gets the node hierarchy used to render z-axis */
get: function () {
return this._zAxis;
},
enumerable: false,
configurable: true
});
/**
* Force the viewer to update
* @param position defines the position of the viewer
* @param xaxis defines the x axis of the viewer
* @param yaxis defines the y axis of the viewer
* @param zaxis defines the z axis of the viewer
*/
AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
this._xAxis.position.copyFrom(position);
this._xAxis.setDirection(xaxis);
this._xAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
this._yAxis.position.copyFrom(position);
this._yAxis.setDirection(yaxis);
this._yAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
this._zAxis.position.copyFrom(position);
this._zAxis.setDirection(zaxis);
this._zAxis.scaling.setAll(this.scaleLines * this._scaleLinesFactor);
};
/**
* Creates an instance of this axes viewer.
* @returns a new axes viewer with instanced meshes
*/
AxesViewer.prototype.createInstance = function () {
var xAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._xAxis);
var yAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._yAxis);
var zAxis = _Gizmos_axisDragGizmo__WEBPACK_IMPORTED_MODULE_2__["AxisDragGizmo"]._CreateArrowInstance(this.scene, this._zAxis);
var axesViewer = new AxesViewer(this.scene, this.scaleLines, null, xAxis, yAxis, zAxis);
axesViewer._instanced = true;
return axesViewer;
};
/** Releases resources */
AxesViewer.prototype.dispose = function () {
if (this._xAxis) {
this._xAxis.dispose(false, !this._instanced);
}
if (this._yAxis) {
this._yAxis.dispose(false, !this._instanced);
}
if (this._zAxis) {
this._zAxis.dispose(false, !this._instanced);
}
this.scene = null;
};
AxesViewer._SetRenderingGroupId = function (node, id) {
node.getChildMeshes().forEach(function (mesh) {
mesh.renderingGroupId = id;
});
};
return AxesViewer;
}());
/***/ }),
/***/ "./Debug/boneAxesViewer.ts":
/*!*********************************!*\
!*** ./Debug/boneAxesViewer.ts ***!
\*********************************/
/*! exports provided: BoneAxesViewer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return BoneAxesViewer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Debug_axesViewer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Debug/axesViewer */ "./Debug/axesViewer.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts");
/**
* The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
* @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
*/
var BoneAxesViewer = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BoneAxesViewer, _super);
/**
* Creates a new BoneAxesViewer
* @param scene defines the hosting scene
* @param bone defines the target bone
* @param mesh defines the target mesh
* @param scaleLines defines a scaling factor for line length (1 by default)
*/
function BoneAxesViewer(scene, bone, mesh, scaleLines) {
if (scaleLines === void 0) { scaleLines = 1; }
var _this = _super.call(this, scene, scaleLines) || this;
/** Gets current position */
_this.pos = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
/** Gets direction of X axis */
_this.xaxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
/** Gets direction of Y axis */
_this.yaxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
/** Gets direction of Z axis */
_this.zaxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this.mesh = mesh;
_this.bone = bone;
return _this;
}
/**
* Force the viewer to update
*/
BoneAxesViewer.prototype.update = function () {
if (!this.mesh || !this.bone) {
return;
}
var bone = this.bone;
bone._markAsDirtyAndCompose();
bone.getAbsolutePositionToRef(this.mesh, this.pos);
bone.getDirectionToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_3__["Axis"].X, this.mesh, this.xaxis);
bone.getDirectionToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_3__["Axis"].Y, this.mesh, this.yaxis);
bone.getDirectionToRef(_Maths_math_axis__WEBPACK_IMPORTED_MODULE_3__["Axis"].Z, this.mesh, this.zaxis);
_super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
};
/** Releases resources */
BoneAxesViewer.prototype.dispose = function () {
if (this.mesh) {
this.mesh = null;
this.bone = null;
_super.prototype.dispose.call(this);
}
};
return BoneAxesViewer;
}(_Debug_axesViewer__WEBPACK_IMPORTED_MODULE_1__["AxesViewer"]));
/***/ }),
/***/ "./Debug/debugLayer.ts":
/*!*****************************!*\
!*** ./Debug/debugLayer.ts ***!
\*****************************/
/*! exports provided: DebugLayerTab, DebugLayer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugLayerTab", function() { return DebugLayerTab; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return DebugLayer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_3__["Scene"].prototype, "debugLayer", {
get: function () {
if (!this._debugLayer) {
this._debugLayer = new DebugLayer(this);
}
return this._debugLayer;
},
enumerable: true,
configurable: true
});
/**
* Enum of inspector action tab
*/
var DebugLayerTab;
(function (DebugLayerTab) {
/**
* Properties tag (default)
*/
DebugLayerTab[DebugLayerTab["Properties"] = 0] = "Properties";
/**
* Debug tab
*/
DebugLayerTab[DebugLayerTab["Debug"] = 1] = "Debug";
/**
* Statistics tab
*/
DebugLayerTab[DebugLayerTab["Statistics"] = 2] = "Statistics";
/**
* Tools tab
*/
DebugLayerTab[DebugLayerTab["Tools"] = 3] = "Tools";
/**
* Settings tab
*/
DebugLayerTab[DebugLayerTab["Settings"] = 4] = "Settings";
})(DebugLayerTab || (DebugLayerTab = {}));
/**
* The debug layer (aka Inspector) is the go to tool in order to better understand
* what is happening in your scene
* @see https://doc.babylonjs.com/features/playground_debuglayer
*/
var DebugLayer = /** @class */ (function () {
/**
* Instantiates a new debug layer.
* The debug layer (aka Inspector) is the go to tool in order to better understand
* what is happening in your scene
* @see https://doc.babylonjs.com/features/playground_debuglayer
* @param scene Defines the scene to inspect
*/
function DebugLayer(scene) {
var _this = this;
this.BJSINSPECTOR = this._getGlobalInspector();
this._scene = scene;
this._scene.onDisposeObservable.add(function () {
// Debug layer
if (_this._scene._debugLayer) {
_this._scene._debugLayer.hide();
}
});
}
Object.defineProperty(DebugLayer.prototype, "onPropertyChangedObservable", {
/**
* Observable triggered when a property is changed through the inspector.
*/
get: function () {
if (this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector) {
return this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable;
}
if (!this._onPropertyChangedObservable) {
this._onPropertyChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
}
return this._onPropertyChangedObservable;
},
enumerable: false,
configurable: true
});
/** Creates the inspector window. */
DebugLayer.prototype._createInspector = function (config) {
if (this.isVisible()) {
return;
}
if (this._onPropertyChangedObservable) {
for (var _i = 0, _a = this._onPropertyChangedObservable.observers; _i < _a.length; _i++) {
var observer = _a[_i];
this.BJSINSPECTOR.Inspector.OnPropertyChangedObservable.add(observer);
}
this._onPropertyChangedObservable.clear();
this._onPropertyChangedObservable = undefined;
}
var userOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ overlay: false, showExplorer: true, showInspector: true, embedMode: false, handleResize: true, enablePopup: true }, config);
this.BJSINSPECTOR = this.BJSINSPECTOR || this._getGlobalInspector();
this.BJSINSPECTOR.Inspector.Show(this._scene, userOptions);
};
/**
* Select a specific entity in the scene explorer and highlight a specific block in that entity property grid
* @param entity defines the entity to select
* @param lineContainerTitles defines the specific blocks to highlight (could be a string or an array of strings)
*/
DebugLayer.prototype.select = function (entity, lineContainerTitles) {
if (this.BJSINSPECTOR) {
if (lineContainerTitles) {
if (Object.prototype.toString.call(lineContainerTitles) == '[object String]') {
this.BJSINSPECTOR.Inspector.MarkLineContainerTitleForHighlighting(lineContainerTitles);
}
else {
this.BJSINSPECTOR.Inspector.MarkMultipleLineContainerTitlesForHighlighting(lineContainerTitles);
}
}
this.BJSINSPECTOR.Inspector.OnSelectionChangeObservable.notifyObservers(entity);
}
};
/** Get the inspector from bundle or global */
DebugLayer.prototype._getGlobalInspector = function () {
// UMD Global name detection from Webpack Bundle UMD Name.
if (typeof INSPECTOR !== 'undefined') {
return INSPECTOR;
}
// In case of module let s check the global emitted from the Inspector entry point.
if (typeof BABYLON !== 'undefined' && typeof BABYLON.Inspector !== 'undefined') {
return BABYLON;
}
return undefined;
};
/**
* Get if the inspector is visible or not.
* @returns true if visible otherwise, false
*/
DebugLayer.prototype.isVisible = function () {
return this.BJSINSPECTOR && this.BJSINSPECTOR.Inspector.IsVisible;
};
/**
* Hide the inspector and close its window.
*/
DebugLayer.prototype.hide = function () {
if (this.BJSINSPECTOR) {
this.BJSINSPECTOR.Inspector.Hide();
}
};
/**
* Update the scene in the inspector
*/
DebugLayer.prototype.setAsActiveScene = function () {
if (this.BJSINSPECTOR) {
this.BJSINSPECTOR.Inspector._SetNewScene(this._scene);
}
};
/**
* Launch the debugLayer.
* @param config Define the configuration of the inspector
* @return a promise fulfilled when the debug layer is visible
*/
DebugLayer.prototype.show = function (config) {
var _this = this;
return new Promise(function (resolve, reject) {
if (typeof _this.BJSINSPECTOR == 'undefined') {
var inspectorUrl = config && config.inspectorURL ? config.inspectorURL : DebugLayer.InspectorURL;
// Load inspector and add it to the DOM
_Misc_tools__WEBPACK_IMPORTED_MODULE_1__["Tools"].LoadScript(inspectorUrl, function () {
_this._createInspector(config);
resolve(_this);
});
}
else {
// Otherwise creates the inspector
_this._createInspector(config);
resolve(_this);
}
});
};
/**
* Define the url to get the inspector script from.
* By default it uses the babylonjs CDN.
* @ignoreNaming
*/
DebugLayer.InspectorURL = "https://unpkg.com/babylonjs-inspector@" + _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].Version + "/babylon.inspector.bundle.js";
return DebugLayer;
}());
/***/ }),
/***/ "./Debug/index.ts":
/*!************************!*\
!*** ./Debug/index.ts ***!
\************************/
/*! exports provided: AxesViewer, BoneAxesViewer, DebugLayerTab, DebugLayer, PhysicsViewer, RayHelper, SkeletonViewer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _axesViewer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./axesViewer */ "./Debug/axesViewer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return _axesViewer__WEBPACK_IMPORTED_MODULE_0__["AxesViewer"]; });
/* harmony import */ var _boneAxesViewer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./boneAxesViewer */ "./Debug/boneAxesViewer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return _boneAxesViewer__WEBPACK_IMPORTED_MODULE_1__["BoneAxesViewer"]; });
/* harmony import */ var _debugLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./debugLayer */ "./Debug/debugLayer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayerTab", function() { return _debugLayer__WEBPACK_IMPORTED_MODULE_2__["DebugLayerTab"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return _debugLayer__WEBPACK_IMPORTED_MODULE_2__["DebugLayer"]; });
/* harmony import */ var _physicsViewer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./physicsViewer */ "./Debug/physicsViewer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return _physicsViewer__WEBPACK_IMPORTED_MODULE_3__["PhysicsViewer"]; });
/* harmony import */ var _rayHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./rayHelper */ "./Debug/rayHelper.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return _rayHelper__WEBPACK_IMPORTED_MODULE_4__["RayHelper"]; });
/* harmony import */ var _skeletonViewer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./skeletonViewer */ "./Debug/skeletonViewer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return _skeletonViewer__WEBPACK_IMPORTED_MODULE_5__["SkeletonViewer"]; });
/* harmony import */ var _ISkeletonViewer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./ISkeletonViewer */ "./Debug/ISkeletonViewer.ts");
/* empty/unused harmony star reexport */
/***/ }),
/***/ "./Debug/physicsViewer.ts":
/*!********************************!*\
!*** ./Debug/physicsViewer.ts ***!
\********************************/
/*! exports provided: PhysicsViewer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return PhysicsViewer; });
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts");
/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Physics/physicsImpostor */ "./Physics/physicsImpostor.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts");
/**
* Used to show the physics impostor around the specific mesh
*/
var PhysicsViewer = /** @class */ (function () {
/**
* Creates a new PhysicsViewer
* @param scene defines the hosting scene
*/
function PhysicsViewer(scene) {
/** @hidden */
this._impostors = [];
/** @hidden */
this._meshes = [];
/** @hidden */
this._numMeshes = 0;
this._debugMeshMeshes = new Array();
this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene;
var physicEngine = this._scene.getPhysicsEngine();
if (physicEngine) {
this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
}
this._utilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__["UtilityLayerRenderer"](this._scene, false);
this._utilityLayer.pickUtilitySceneFirst = false;
this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
}
/** @hidden */
PhysicsViewer.prototype._updateDebugMeshes = function () {
var plugin = this._physicsEnginePlugin;
for (var i = 0; i < this._numMeshes; i++) {
var impostor = this._impostors[i];
if (!impostor) {
continue;
}
if (impostor.isDisposed) {
this.hideImpostor(this._impostors[i--]);
}
else {
if (impostor.type === _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__["PhysicsImpostor"].MeshImpostor) {
continue;
}
var mesh = this._meshes[i];
if (mesh && plugin) {
plugin.syncMeshWithImpostor(mesh, impostor);
}
}
}
};
/**
* Renders a specified physic impostor
* @param impostor defines the impostor to render
* @param targetMesh defines the mesh represented by the impostor
* @returns the new debug mesh used to render the impostor
*/
PhysicsViewer.prototype.showImpostor = function (impostor, targetMesh) {
if (!this._scene) {
return null;
}
for (var i = 0; i < this._numMeshes; i++) {
if (this._impostors[i] == impostor) {
return null;
}
}
var debugMesh = this._getDebugMesh(impostor, targetMesh);
if (debugMesh) {
this._impostors[this._numMeshes] = impostor;
this._meshes[this._numMeshes] = debugMesh;
if (this._numMeshes === 0) {
this._renderFunction = this._updateDebugMeshes.bind(this);
this._scene.registerBeforeRender(this._renderFunction);
}
this._numMeshes++;
}
return debugMesh;
};
/**
* Hides a specified physic impostor
* @param impostor defines the impostor to hide
*/
PhysicsViewer.prototype.hideImpostor = function (impostor) {
if (!impostor || !this._scene || !this._utilityLayer) {
return;
}
var removed = false;
var utilityLayerScene = this._utilityLayer.utilityLayerScene;
for (var i = 0; i < this._numMeshes; i++) {
if (this._impostors[i] == impostor) {
var mesh = this._meshes[i];
if (!mesh) {
continue;
}
utilityLayerScene.removeMesh(mesh);
mesh.dispose();
var index = this._debugMeshMeshes.indexOf(mesh);
if (index > -1) {
this._debugMeshMeshes.splice(index, 1);
}
this._numMeshes--;
if (this._numMeshes > 0) {
this._meshes[i] = this._meshes[this._numMeshes];
this._impostors[i] = this._impostors[this._numMeshes];
this._meshes[this._numMeshes] = null;
this._impostors[this._numMeshes] = null;
}
else {
this._meshes[0] = null;
this._impostors[0] = null;
}
removed = true;
break;
}
}
if (removed && this._numMeshes === 0) {
this._scene.unregisterBeforeRender(this._renderFunction);
}
};
PhysicsViewer.prototype._getDebugMaterial = function (scene) {
if (!this._debugMaterial) {
this._debugMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]('', scene);
this._debugMaterial.wireframe = true;
this._debugMaterial.emissiveColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].White();
this._debugMaterial.disableLighting = true;
}
return this._debugMaterial;
};
PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
if (!this._debugBoxMesh) {
this._debugBoxMesh = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_1__["BoxBuilder"].CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
this._debugBoxMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity();
this._debugBoxMesh.material = this._getDebugMaterial(scene);
this._debugBoxMesh.setEnabled(false);
}
return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
};
PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
if (!this._debugSphereMesh) {
this._debugSphereMesh = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_2__["SphereBuilder"].CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
this._debugSphereMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity();
this._debugSphereMesh.material = this._getDebugMaterial(scene);
this._debugSphereMesh.setEnabled(false);
}
return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
};
PhysicsViewer.prototype._getDebugCylinderMesh = function (scene) {
if (!this._debugCylinderMesh) {
this._debugCylinderMesh = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_9__["CylinderBuilder"].CreateCylinder('physicsBodyCylinderViewMesh', { diameterTop: 1, diameterBottom: 1, height: 1 }, scene);
this._debugCylinderMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].Identity();
this._debugCylinderMesh.material = this._getDebugMaterial(scene);
this._debugCylinderMesh.setEnabled(false);
}
return this._debugCylinderMesh.createInstance('physicsBodyBoxViewInstance');
};
PhysicsViewer.prototype._getDebugMeshMesh = function (mesh, scene) {
var wireframeOver = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_0__["Mesh"](mesh.name, scene, null, mesh);
wireframeOver.position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero();
wireframeOver.setParent(mesh);
wireframeOver.material = this._getDebugMaterial(scene);
this._debugMeshMeshes.push(wireframeOver);
return wireframeOver;
};
PhysicsViewer.prototype._getDebugMesh = function (impostor, targetMesh) {
var _this = this;
if (!this._utilityLayer) {
return null;
}
// Only create child impostor debug meshes when evaluating the parent
if (targetMesh && targetMesh.parent && targetMesh.parent.physicsImpostor) {
return null;
}
var mesh = null;
var utilityLayerScene = this._utilityLayer.utilityLayerScene;
switch (impostor.type) {
case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__["PhysicsImpostor"].BoxImpostor:
mesh = this._getDebugBoxMesh(utilityLayerScene);
impostor.getBoxSizeToRef(mesh.scaling);
break;
case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__["PhysicsImpostor"].SphereImpostor:
mesh = this._getDebugSphereMesh(utilityLayerScene);
var radius = impostor.getRadius();
mesh.scaling.x = radius * 2;
mesh.scaling.y = radius * 2;
mesh.scaling.z = radius * 2;
break;
case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__["PhysicsImpostor"].MeshImpostor:
if (targetMesh) {
mesh = this._getDebugMeshMesh(targetMesh, utilityLayerScene);
}
break;
case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__["PhysicsImpostor"].NoImpostor:
if (targetMesh) {
// Handle compound impostors
var childMeshes = targetMesh.getChildMeshes().filter(function (c) { return c.physicsImpostor ? 1 : 0; });
childMeshes.forEach(function (m) {
var a = _this._getDebugBoxMesh(utilityLayerScene);
a.parent = m;
});
}
break;
case _Physics_physicsImpostor__WEBPACK_IMPORTED_MODULE_7__["PhysicsImpostor"].CylinderImpostor:
mesh = this._getDebugCylinderMesh(utilityLayerScene);
var bi = impostor.object.getBoundingInfo();
mesh.scaling.x = bi.boundingBox.maximum.x - bi.boundingBox.minimum.x;
mesh.scaling.y = bi.boundingBox.maximum.y - bi.boundingBox.minimum.y;
mesh.scaling.z = bi.boundingBox.maximum.z - bi.boundingBox.minimum.z;
break;
}
return mesh;
};
/** Releases all resources */
PhysicsViewer.prototype.dispose = function () {
var count = this._numMeshes;
for (var index = 0; index < count; index++) {
this.hideImpostor(this._impostors[0]);
}
if (this._debugBoxMesh) {
this._debugBoxMesh.dispose();
}
if (this._debugSphereMesh) {
this._debugSphereMesh.dispose();
}
if (this._debugCylinderMesh) {
this._debugCylinderMesh.dispose();
}
if (this._debugMaterial) {
this._debugMaterial.dispose();
}
this._impostors.length = 0;
this._scene = null;
this._physicsEnginePlugin = null;
if (this._utilityLayer) {
this._utilityLayer.dispose();
this._utilityLayer = null;
}
};
return PhysicsViewer;
}());
/***/ }),
/***/ "./Debug/rayHelper.ts":
/*!****************************!*\
!*** ./Debug/rayHelper.ts ***!
\****************************/
/*! exports provided: RayHelper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return RayHelper; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts");
/**
* As raycast might be hard to debug, the RayHelper can help rendering the different rays
* in order to better appreciate the issue one might have.
* @see https://doc.babylonjs.com/babylon101/raycasts#debugging
*/
var RayHelper = /** @class */ (function () {
/**
* Instantiate a new ray helper.
* As raycast might be hard to debug, the RayHelper can help rendering the different rays
* in order to better appreciate the issue one might have.
* @see https://doc.babylonjs.com/babylon101/raycasts#debugging
* @param ray Defines the ray we are currently tryin to visualize
*/
function RayHelper(ray) {
this.ray = ray;
}
/**
* Helper function to create a colored helper in a scene in one line.
* @param ray Defines the ray we are currently tryin to visualize
* @param scene Defines the scene the ray is used in
* @param color Defines the color we want to see the ray in
* @returns The newly created ray helper.
*/
RayHelper.CreateAndShow = function (ray, scene, color) {
var helper = new RayHelper(ray);
helper.show(scene, color);
return helper;
};
/**
* Shows the ray we are willing to debug.
* @param scene Defines the scene the ray needs to be rendered in
* @param color Defines the color the ray needs to be rendered in
*/
RayHelper.prototype.show = function (scene, color) {
if (!this._renderFunction && this.ray) {
var ray = this.ray;
this._renderFunction = this._render.bind(this);
this._scene = scene;
this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
this._renderLine = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"].CreateLines("ray", this._renderPoints, scene, true);
this._renderLine.isPickable = false;
if (this._renderFunction) {
this._scene.registerBeforeRender(this._renderFunction);
}
}
if (color && this._renderLine) {
this._renderLine.color.copyFrom(color);
}
};
/**
* Hides the ray we are debugging.
*/
RayHelper.prototype.hide = function () {
if (this._renderFunction && this._scene) {
this._scene.unregisterBeforeRender(this._renderFunction);
this._scene = null;
this._renderFunction = null;
if (this._renderLine) {
this._renderLine.dispose();
this._renderLine = null;
}
this._renderPoints = [];
}
};
RayHelper.prototype._render = function () {
var ray = this.ray;
if (!ray) {
return;
}
var point = this._renderPoints[1];
var len = Math.min(ray.length, 1000000);
point.copyFrom(ray.direction);
point.scaleInPlace(len);
point.addInPlace(ray.origin);
_Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"].CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
};
/**
* Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
* @param mesh Defines the mesh we want the helper attached to
* @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
* @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
* @param length Defines the length of the ray
*/
RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
var _this = this;
this._attachedToMesh = mesh;
var ray = this.ray;
if (!ray) {
return;
}
if (!ray.direction) {
ray.direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
}
if (!ray.origin) {
ray.origin = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
}
if (length) {
ray.length = length;
}
if (!meshSpaceOrigin) {
meshSpaceOrigin = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero();
}
if (!meshSpaceDirection) {
// -1 so that this will work with Mesh.lookAt
meshSpaceDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, -1);
}
if (!this._scene) {
this._scene = mesh.getScene();
}
if (!this._meshSpaceDirection) {
this._meshSpaceDirection = meshSpaceDirection.clone();
this._meshSpaceOrigin = meshSpaceOrigin.clone();
}
else {
this._meshSpaceDirection.copyFrom(meshSpaceDirection);
this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
}
if (!this._onAfterRenderObserver) {
this._onAfterRenderObserver = this._scene.onBeforeRenderObservable.add(function () { return _this._updateToMesh(); });
this._onAfterStepObserver = this._scene.onAfterStepObservable.add(function () { return _this._updateToMesh(); });
}
// force world matrix computation before the first ray helper computation
this._attachedToMesh.computeWorldMatrix(true);
this._updateToMesh();
};
/**
* Detach the ray helper from the mesh it has previously been attached to.
*/
RayHelper.prototype.detachFromMesh = function () {
if (this._attachedToMesh && this._scene) {
if (this._onAfterRenderObserver) {
this._scene.onBeforeRenderObservable.remove(this._onAfterRenderObserver);
this._scene.onAfterStepObservable.remove(this._onAfterStepObserver);
}
this._attachedToMesh = null;
this._onAfterRenderObserver = null;
this._onAfterStepObserver = null;
this._scene = null;
}
};
RayHelper.prototype._updateToMesh = function () {
var ray = this.ray;
if (!this._attachedToMesh || !ray) {
return;
}
if (this._attachedToMesh._isDisposed) {
this.detachFromMesh();
return;
}
this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
};
/**
* Dispose the helper and release its associated resources.
*/
RayHelper.prototype.dispose = function () {
this.hide();
this.detachFromMesh();
this.ray = null;
};
return RayHelper;
}());
/***/ }),
/***/ "./Debug/skeletonViewer.ts":
/*!*********************************!*\
!*** ./Debug/skeletonViewer.ts ***!
\*********************************/
/*! exports provided: SkeletonViewer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return SkeletonViewer; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts");
/* harmony import */ var _Meshes_Builders_shapeBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Meshes/Builders/shapeBuilder */ "./Meshes/Builders/shapeBuilder.ts");
/**
* Class used to render a debug view of a given skeleton
* @see http://www.babylonjs-playground.com/#1BZJVJ#8
*/
var SkeletonViewer = /** @class */ (function () {
/**
* Creates a new SkeletonViewer
* @param skeleton defines the skeleton to render
* @param mesh defines the mesh attached to the skeleton
* @param scene defines the hosting scene
* @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
* @param renderingGroupId defines the rendering group id to use with the viewer
* @param options All of the extra constructor options for the SkeletonViewer
*/
function SkeletonViewer(
/** defines the skeleton to render */
skeleton,
/** defines the mesh attached to the skeleton */
mesh,
/** The Scene scope*/
scene,
/** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
autoUpdateBonesMatrices,
/** defines the rendering group id to use with the viewer */
renderingGroupId,
/** is the options for the viewer */
options) {
if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
if (renderingGroupId === void 0) { renderingGroupId = 3; }
if (options === void 0) { options = {}; }
var _a, _c, _d, _e, _f, _g, _h, _j, _k, _l;
this.skeleton = skeleton;
this.mesh = mesh;
this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
this.renderingGroupId = renderingGroupId;
this.options = options;
/** Gets or sets the color used to render the skeleton */
this.color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_1__["Color3"].White();
/** Array of the points of the skeleton fo the line view. */
this._debugLines = new Array();
/** If SkeletonViewer is enabled. */
this._isEnabled = false;
/** SkeletonViewer render observable. */
this._obs = null;
this._scene = scene;
this._ready = false;
//Defaults
options.pauseAnimations = (_a = options.pauseAnimations) !== null && _a !== void 0 ? _a : true;
options.returnToRest = (_c = options.returnToRest) !== null && _c !== void 0 ? _c : true;
options.displayMode = (_d = options.displayMode) !== null && _d !== void 0 ? _d : SkeletonViewer.DISPLAY_LINES;
options.displayOptions = (_e = options.displayOptions) !== null && _e !== void 0 ? _e : {};
options.displayOptions.midStep = (_f = options.displayOptions.midStep) !== null && _f !== void 0 ? _f : 0.235;
options.displayOptions.midStepFactor = (_g = options.displayOptions.midStepFactor) !== null && _g !== void 0 ? _g : 0.155;
options.displayOptions.sphereBaseSize = (_h = options.displayOptions.sphereBaseSize) !== null && _h !== void 0 ? _h : 0.15;
options.displayOptions.sphereScaleUnit = (_j = options.displayOptions.sphereScaleUnit) !== null && _j !== void 0 ? _j : 2;
options.displayOptions.sphereFactor = (_k = options.displayOptions.sphereFactor) !== null && _k !== void 0 ? _k : 0.865;
options.computeBonesUsingShaders = (_l = options.computeBonesUsingShaders) !== null && _l !== void 0 ? _l : true;
var boneIndices = mesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].MatricesIndicesKind);
var boneWeights = mesh.getVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].MatricesWeightsKind);
this._boneIndices = new Set();
if (boneIndices && boneWeights) {
for (var i = 0; i < boneIndices.length; ++i) {
var index = boneIndices[i], weight = boneWeights[i];
if (weight !== 0) {
this._boneIndices.add(index);
}
}
}
/* Create Utility Layer */
this._utilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_4__["UtilityLayerRenderer"](this._scene, false);
this._utilityLayer.pickUtilitySceneFirst = false;
this._utilityLayer.utilityLayerScene.autoClearDepthAndStencil = true;
var displayMode = this.options.displayMode || 0;
if (displayMode > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
displayMode = SkeletonViewer.DISPLAY_LINES;
}
this.displayMode = displayMode;
//Prep the Systems
this.update();
this._bindObs();
}
Object.defineProperty(SkeletonViewer.prototype, "scene", {
/** Gets the Scene. */
get: function () {
return this._scene;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SkeletonViewer.prototype, "utilityLayer", {
/** Gets the utilityLayer. */
get: function () {
return this._utilityLayer;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SkeletonViewer.prototype, "isReady", {
/** Checks Ready Status. */
get: function () {
return this._ready;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SkeletonViewer.prototype, "ready", {
/** Sets Ready Status. */
set: function (value) {
this._ready = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SkeletonViewer.prototype, "debugMesh", {
/** Gets the debugMesh */
get: function () {
return this._debugMesh;
},
/** Sets the debugMesh */
set: function (value) {
this._debugMesh = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SkeletonViewer.prototype, "material", {
/** Gets the material */
get: function () {
return this.material;
},
/** Sets the material */
set: function (value) {
this.material = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SkeletonViewer.prototype, "displayMode", {
/** Gets the material */
get: function () {
return this.options.displayMode || SkeletonViewer.DISPLAY_LINES;
},
/** Sets the material */
set: function (value) {
if (value > SkeletonViewer.DISPLAY_SPHERE_AND_SPURS) {
value = SkeletonViewer.DISPLAY_LINES;
}
this.options.displayMode = value;
},
enumerable: false,
configurable: true
});
/** The Dynamic bindings for the update functions */
SkeletonViewer.prototype._bindObs = function () {
var _this = this;
switch (this.displayMode) {
case SkeletonViewer.DISPLAY_LINES: {
this._obs = this.scene.onBeforeRenderObservable.add(function () {
_this._displayLinesUpdate();
});
break;
}
}
};
/** Update the viewer to sync with current skeleton state, only used to manually update. */
SkeletonViewer.prototype.update = function () {
switch (this.displayMode) {
case SkeletonViewer.DISPLAY_LINES: {
this._displayLinesUpdate();
break;
}
case SkeletonViewer.DISPLAY_SPHERES: {
this._buildSpheresAndSpurs(true);
break;
}
case SkeletonViewer.DISPLAY_SPHERE_AND_SPURS: {
this._buildSpheresAndSpurs(false);
break;
}
}
};
Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
get: function () {
return this._isEnabled;
},
/** Gets or sets a boolean indicating if the viewer is enabled */
set: function (value) {
if (this.isEnabled === value) {
return;
}
this._isEnabled = value;
if (this.debugMesh) {
this.debugMesh.setEnabled(value);
}
if (value && !this._obs) {
this._bindObs();
}
else if (!value && this._obs) {
this.scene.onBeforeRenderObservable.remove(this._obs);
this._obs = null;
}
},
enumerable: false,
configurable: true
});
SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
if (x === void 0) { x = 0; }
if (y === void 0) { y = 0; }
if (z === void 0) { z = 0; }
var tmat = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Matrix[0];
var parentBone = bone.getParent();
tmat.copyFrom(bone.getLocalMatrix());
if (x !== 0 || y !== 0 || z !== 0) {
var tmat2 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"].Matrix[1];
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].IdentityToRef(tmat2);
tmat2.setTranslationFromFloats(x, y, z);
tmat2.multiplyToRef(tmat, tmat);
}
if (parentBone) {
tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
}
tmat.multiplyToRef(meshMat, tmat);
position.x = tmat.m[12];
position.y = tmat.m[13];
position.z = tmat.m[14];
};
SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
var len = bones.length;
var mesh = this.mesh._effectiveMesh;
var meshPos = mesh.position;
var idx = 0;
for (var i = 0; i < len; i++) {
var bone = bones[i];
var points = this._debugLines[idx];
if (bone._index === -1 || !this._boneIndices.has(bone.getIndex())) {
continue;
}
if (!points) {
points = [_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()];
this._debugLines[idx] = points;
}
this._getBonePosition(points[0], bone, meshMat);
this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
points[0].subtractInPlace(meshPos);
points[1].subtractInPlace(meshPos);
idx++;
}
};
SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones) {
var len = bones.length;
var boneNum = 0;
var mesh = this.mesh._effectiveMesh;
var meshPos = mesh.position;
for (var i = len - 1; i >= 0; i--) {
var childBone = bones[i];
var parentBone = childBone.getParent();
if (!parentBone || !this._boneIndices.has(childBone.getIndex())) {
continue;
}
var points = this._debugLines[boneNum];
if (!points) {
points = [_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero()];
this._debugLines[boneNum] = points;
}
childBone.getAbsolutePositionToRef(mesh, points[0]);
parentBone.getAbsolutePositionToRef(mesh, points[1]);
points[0].subtractInPlace(meshPos);
points[1].subtractInPlace(meshPos);
boneNum++;
}
};
/** function to revert the mesh and scene back to the initial state. */
SkeletonViewer.prototype._revert = function (animationState) {
if (this.options.pauseAnimations) {
this.scene.animationsEnabled = animationState;
}
};
/** function to build and bind sphere joint points and spur bone representations. */
SkeletonViewer.prototype._buildSpheresAndSpurs = function (spheresOnly) {
var _a;
if (spheresOnly === void 0) { spheresOnly = true; }
if (this._debugMesh) {
this._debugMesh.dispose();
this._debugMesh = null;
this.ready = false;
}
this._ready = false;
var scene = this.scene;
var bones = this.skeleton.bones;
var spheres = [];
var spurs = [];
var animationState = scene.animationsEnabled;
try {
if (this.options.pauseAnimations) {
scene.animationsEnabled = false;
}
if (this.options.returnToRest) {
this.skeleton.returnToRest();
}
if (this.autoUpdateBonesMatrices) {
this.skeleton.computeAbsoluteTransforms();
}
var longestBoneLength_1 = Number.NEGATIVE_INFINITY;
var getAbsoluteRestPose_1 = function (bone, matrix) {
if (bone === null || bone._index === -1) {
matrix.copyFrom(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Identity());
return;
}
getAbsoluteRestPose_1(bone.getParent(), matrix);
bone.getBindPose().multiplyToRef(matrix, matrix);
return;
};
var displayOptions_1 = this.options.displayOptions || {};
var _loop_1 = function (i) {
var bone = bones[i];
if (bone._index === -1 || !this_1._boneIndices.has(bone.getIndex())) {
return "continue";
}
var boneAbsoluteRestTransform = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"]();
getAbsoluteRestPose_1(bone, boneAbsoluteRestTransform);
var anchorPoint = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
boneAbsoluteRestTransform.decompose(undefined, undefined, anchorPoint);
bone.children.forEach(function (bc, i) {
var childAbsoluteRestTransform = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"]();
bc.getRestPose().multiplyToRef(boneAbsoluteRestTransform, childAbsoluteRestTransform);
var childPoint = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
childAbsoluteRestTransform.decompose(undefined, undefined, childPoint);
var distanceFromParent = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Distance(anchorPoint, childPoint);
if (distanceFromParent > longestBoneLength_1) {
longestBoneLength_1 = distanceFromParent;
}
if (spheresOnly) {
return;
}
var dir = childPoint.clone().subtract(anchorPoint.clone());
var h = dir.length();
var up = dir.normalize().scale(h);
var midStep = displayOptions_1.midStep || 0.165;
var midStepFactor = displayOptions_1.midStepFactor || 0.215;
var up0 = up.scale(midStep);
var spur = _Meshes_Builders_shapeBuilder__WEBPACK_IMPORTED_MODULE_7__["ShapeBuilder"].ExtrudeShapeCustom(bc.name + ':spur', {
shape: [
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, -1, 0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, 1, 0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](-1, 1, 0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](-1, -1, 0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, -1, 0)
],
path: [_Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero(), up0, up],
scaleFunction: function (i) {
switch (i) {
case 0:
case 2:
return 0;
case 1:
return h * midStepFactor;
}
return 0;
},
sideOrientation: _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].DEFAULTSIDE,
updatable: false
}, scene);
spur.convertToFlatShadedMesh();
var numVertices = spur.getTotalVertices();
var mwk = [], mik = [];
for (var i_1 = 0; i_1 < numVertices; i_1++) {
mwk.push(1, 0, 0, 0);
mik.push(bone.getIndex(), 0, 0, 0);
}
spur.position = anchorPoint.clone();
spur.setVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].MatricesWeightsKind, mwk, false);
spur.setVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].MatricesIndicesKind, mik, false);
spurs.push(spur);
});
var sphereBaseSize = displayOptions_1.sphereBaseSize || 0.2;
var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__["SphereBuilder"].CreateSphere(bone.name + ':sphere', {
segments: 6,
diameter: sphereBaseSize,
updatable: false
}, scene);
var numVertices = sphere.getTotalVertices();
var mwk = [], mik = [];
for (var i_2 = 0; i_2 < numVertices; i_2++) {
mwk.push(1, 0, 0, 0);
mik.push(bone.getIndex(), 0, 0, 0);
}
sphere.setVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].MatricesWeightsKind, mwk, false);
sphere.setVerticesData(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].MatricesIndicesKind, mik, false);
sphere.position = anchorPoint.clone();
spheres.push([sphere, bone]);
};
var this_1 = this;
for (var i = 0; i < bones.length; i++) {
_loop_1(i);
}
var sphereScaleUnit = displayOptions_1.sphereScaleUnit || 2;
var sphereFactor = displayOptions_1.sphereFactor || 0.85;
var meshes = [];
for (var i = 0; i < spheres.length; i++) {
var _c = spheres[i], sphere = _c[0], bone = _c[1];
var scale = 1 / (sphereScaleUnit / longestBoneLength_1);
var _stepsOut = 0;
var _b = bone;
while ((_b.getParent()) && _b.getParent().getIndex() !== -1) {
_stepsOut++;
_b = _b.getParent();
}
sphere.scaling.scaleInPlace(scale * Math.pow(sphereFactor, _stepsOut));
meshes.push(sphere);
}
this.debugMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].MergeMeshes(meshes.concat(spurs), true, true);
if (this.debugMesh) {
this.debugMesh.renderingGroupId = this.renderingGroupId;
this.debugMesh.skeleton = this.skeleton;
this.debugMesh.parent = this.mesh;
this.debugMesh.computeBonesUsingShaders = (_a = this.options.computeBonesUsingShaders) !== null && _a !== void 0 ? _a : true;
this.debugMesh.alwaysSelectAsActiveMesh = true;
}
this._revert(animationState);
this.ready = true;
}
catch (err) {
console.error(err);
this._revert(animationState);
this.dispose();
}
};
/** Update the viewer to sync with current skeleton state, only used for the line display. */
SkeletonViewer.prototype._displayLinesUpdate = function () {
if (!this._utilityLayer) {
return;
}
if (this.autoUpdateBonesMatrices) {
this.skeleton.computeAbsoluteTransforms();
}
var mesh = this.mesh._effectiveMesh;
if (this.skeleton.bones[0].length === undefined) {
this._getLinesForBonesNoLength(this.skeleton.bones);
}
else {
this._getLinesForBonesWithLength(this.skeleton.bones, mesh.getWorldMatrix());
}
var targetScene = this._utilityLayer.utilityLayerScene;
if (targetScene) {
if (!this._debugMesh) {
this._debugMesh = _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_3__["LinesBuilder"].CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, targetScene);
this._debugMesh.renderingGroupId = this.renderingGroupId;
}
else {
_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_3__["LinesBuilder"].CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, targetScene);
}
this._debugMesh.position.copyFrom(this.mesh.position);
this._debugMesh.color = this.color;
}
};
/** Changes the displayMode of the skeleton viewer
* @param mode The displayMode numerical value
*/
SkeletonViewer.prototype.changeDisplayMode = function (mode) {
var wasEnabled = (this.isEnabled) ? true : false;
if (this.displayMode !== mode) {
this.isEnabled = false;
if (this._debugMesh) {
this._debugMesh.dispose();
this._debugMesh = null;
this.ready = false;
}
this.displayMode = mode;
this.update();
this._bindObs();
this.isEnabled = wasEnabled;
}
};
/** Changes the displayMode of the skeleton viewer
* @param option String of the option name
* @param value The numerical option value
*/
SkeletonViewer.prototype.changeDisplayOptions = function (option, value) {
var wasEnabled = (this.isEnabled) ? true : false;
this.options.displayOptions[option] = value;
this.isEnabled = false;
if (this._debugMesh) {
this._debugMesh.dispose();
this._debugMesh = null;
this.ready = false;
}
this.update();
this._bindObs();
this.isEnabled = wasEnabled;
};
/** Release associated resources */
SkeletonViewer.prototype.dispose = function () {
this.isEnabled = false;
if (this._debugMesh) {
this._debugMesh.dispose();
this._debugMesh = null;
}
if (this._utilityLayer) {
this._utilityLayer.dispose();
this._utilityLayer = null;
}
this.ready = false;
};
/** public Display constants BABYLON.SkeletonViewer.DISPLAY_LINES */
SkeletonViewer.DISPLAY_LINES = 0;
/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERES */
SkeletonViewer.DISPLAY_SPHERES = 1;
/** public Display constants BABYLON.SkeletonViewer.DISPLAY_SPHERE_AND_SPURS */
SkeletonViewer.DISPLAY_SPHERE_AND_SPURS = 2;
return SkeletonViewer;
}());
/***/ }),
/***/ "./DeviceInput/InputDevices/deviceEnums.ts":
/*!*************************************************!*\
!*** ./DeviceInput/InputDevices/deviceEnums.ts ***!
\*************************************************/
/*! exports provided: DeviceType, PointerInput, DualShockInput, XboxInput, SwitchInput */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceType", function() { return DeviceType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInput", function() { return PointerInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DualShockInput", function() { return DualShockInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XboxInput", function() { return XboxInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SwitchInput", function() { return SwitchInput; });
/**
* Enum for Device Types
*/
var DeviceType;
(function (DeviceType) {
/** Generic */
DeviceType[DeviceType["Generic"] = 0] = "Generic";
/** Keyboard */
DeviceType[DeviceType["Keyboard"] = 1] = "Keyboard";
/** Mouse */
DeviceType[DeviceType["Mouse"] = 2] = "Mouse";
/** Touch Pointers */
DeviceType[DeviceType["Touch"] = 3] = "Touch";
/** PS4 Dual Shock */
DeviceType[DeviceType["DualShock"] = 4] = "DualShock";
/** Xbox */
DeviceType[DeviceType["Xbox"] = 5] = "Xbox";
/** Switch Controller */
DeviceType[DeviceType["Switch"] = 6] = "Switch";
})(DeviceType || (DeviceType = {}));
// Device Enums
/**
* Enum for All Pointers (Touch/Mouse)
*/
var PointerInput;
(function (PointerInput) {
/** Horizontal Axis */
PointerInput[PointerInput["Horizontal"] = 0] = "Horizontal";
/** Vertical Axis */
PointerInput[PointerInput["Vertical"] = 1] = "Vertical";
/** Left Click or Touch */
PointerInput[PointerInput["LeftClick"] = 2] = "LeftClick";
/** Middle Click */
PointerInput[PointerInput["MiddleClick"] = 3] = "MiddleClick";
/** Right Click */
PointerInput[PointerInput["RightClick"] = 4] = "RightClick";
/** Browser Back */
PointerInput[PointerInput["BrowserBack"] = 5] = "BrowserBack";
/** Browser Forward */
PointerInput[PointerInput["BrowserForward"] = 6] = "BrowserForward";
})(PointerInput || (PointerInput = {}));
/**
* Enum for Dual Shock Gamepad
*/
var DualShockInput;
(function (DualShockInput) {
/** Cross */
DualShockInput[DualShockInput["Cross"] = 0] = "Cross";
/** Circle */
DualShockInput[DualShockInput["Circle"] = 1] = "Circle";
/** Square */
DualShockInput[DualShockInput["Square"] = 2] = "Square";
/** Triangle */
DualShockInput[DualShockInput["Triangle"] = 3] = "Triangle";
/** L1 */
DualShockInput[DualShockInput["L1"] = 4] = "L1";
/** R1 */
DualShockInput[DualShockInput["R1"] = 5] = "R1";
/** L2 */
DualShockInput[DualShockInput["L2"] = 6] = "L2";
/** R2 */
DualShockInput[DualShockInput["R2"] = 7] = "R2";
/** Share */
DualShockInput[DualShockInput["Share"] = 8] = "Share";
/** Options */
DualShockInput[DualShockInput["Options"] = 9] = "Options";
/** L3 */
DualShockInput[DualShockInput["L3"] = 10] = "L3";
/** R3 */
DualShockInput[DualShockInput["R3"] = 11] = "R3";
/** DPadUp */
DualShockInput[DualShockInput["DPadUp"] = 12] = "DPadUp";
/** DPadDown */
DualShockInput[DualShockInput["DPadDown"] = 13] = "DPadDown";
/** DPadLeft */
DualShockInput[DualShockInput["DPadLeft"] = 14] = "DPadLeft";
/** DRight */
DualShockInput[DualShockInput["DPadRight"] = 15] = "DPadRight";
/** Home */
DualShockInput[DualShockInput["Home"] = 16] = "Home";
/** TouchPad */
DualShockInput[DualShockInput["TouchPad"] = 17] = "TouchPad";
/** LStickXAxis */
DualShockInput[DualShockInput["LStickXAxis"] = 18] = "LStickXAxis";
/** LStickYAxis */
DualShockInput[DualShockInput["LStickYAxis"] = 19] = "LStickYAxis";
/** RStickXAxis */
DualShockInput[DualShockInput["RStickXAxis"] = 20] = "RStickXAxis";
/** RStickYAxis */
DualShockInput[DualShockInput["RStickYAxis"] = 21] = "RStickYAxis";
})(DualShockInput || (DualShockInput = {}));
/**
* Enum for Xbox Gamepad
*/
var XboxInput;
(function (XboxInput) {
/** A */
XboxInput[XboxInput["A"] = 0] = "A";
/** B */
XboxInput[XboxInput["B"] = 1] = "B";
/** X */
XboxInput[XboxInput["X"] = 2] = "X";
/** Y */
XboxInput[XboxInput["Y"] = 3] = "Y";
/** LB */
XboxInput[XboxInput["LB"] = 4] = "LB";
/** RB */
XboxInput[XboxInput["RB"] = 5] = "RB";
/** LT */
XboxInput[XboxInput["LT"] = 6] = "LT";
/** RT */
XboxInput[XboxInput["RT"] = 7] = "RT";
/** Back */
XboxInput[XboxInput["Back"] = 8] = "Back";
/** Start */
XboxInput[XboxInput["Start"] = 9] = "Start";
/** LS */
XboxInput[XboxInput["LS"] = 10] = "LS";
/** RS */
XboxInput[XboxInput["RS"] = 11] = "RS";
/** DPadUp */
XboxInput[XboxInput["DPadUp"] = 12] = "DPadUp";
/** DPadDown */
XboxInput[XboxInput["DPadDown"] = 13] = "DPadDown";
/** DPadLeft */
XboxInput[XboxInput["DPadLeft"] = 14] = "DPadLeft";
/** DRight */
XboxInput[XboxInput["DPadRight"] = 15] = "DPadRight";
/** Home */
XboxInput[XboxInput["Home"] = 16] = "Home";
/** LStickXAxis */
XboxInput[XboxInput["LStickXAxis"] = 17] = "LStickXAxis";
/** LStickYAxis */
XboxInput[XboxInput["LStickYAxis"] = 18] = "LStickYAxis";
/** RStickXAxis */
XboxInput[XboxInput["RStickXAxis"] = 19] = "RStickXAxis";
/** RStickYAxis */
XboxInput[XboxInput["RStickYAxis"] = 20] = "RStickYAxis";
})(XboxInput || (XboxInput = {}));
/**
* Enum for Switch (Pro/JoyCon L+R) Gamepad
*/
var SwitchInput;
(function (SwitchInput) {
/** B */
SwitchInput[SwitchInput["B"] = 0] = "B";
/** A */
SwitchInput[SwitchInput["A"] = 1] = "A";
/** Y */
SwitchInput[SwitchInput["Y"] = 2] = "Y";
/** X */
SwitchInput[SwitchInput["X"] = 3] = "X";
/** L */
SwitchInput[SwitchInput["L"] = 4] = "L";
/** R */
SwitchInput[SwitchInput["R"] = 5] = "R";
/** ZL */
SwitchInput[SwitchInput["ZL"] = 6] = "ZL";
/** ZR */
SwitchInput[SwitchInput["ZR"] = 7] = "ZR";
/** Minus */
SwitchInput[SwitchInput["Minus"] = 8] = "Minus";
/** Plus */
SwitchInput[SwitchInput["Plus"] = 9] = "Plus";
/** LS */
SwitchInput[SwitchInput["LS"] = 10] = "LS";
/** RS */
SwitchInput[SwitchInput["RS"] = 11] = "RS";
/** DPadUp */
SwitchInput[SwitchInput["DPadUp"] = 12] = "DPadUp";
/** DPadDown */
SwitchInput[SwitchInput["DPadDown"] = 13] = "DPadDown";
/** DPadLeft */
SwitchInput[SwitchInput["DPadLeft"] = 14] = "DPadLeft";
/** DRight */
SwitchInput[SwitchInput["DPadRight"] = 15] = "DPadRight";
/** Home */
SwitchInput[SwitchInput["Home"] = 16] = "Home";
/** Capture */
SwitchInput[SwitchInput["Capture"] = 17] = "Capture";
/** LStickXAxis */
SwitchInput[SwitchInput["LStickXAxis"] = 18] = "LStickXAxis";
/** LStickYAxis */
SwitchInput[SwitchInput["LStickYAxis"] = 19] = "LStickYAxis";
/** RStickXAxis */
SwitchInput[SwitchInput["RStickXAxis"] = 20] = "RStickXAxis";
/** RStickYAxis */
SwitchInput[SwitchInput["RStickYAxis"] = 21] = "RStickYAxis";
})(SwitchInput || (SwitchInput = {}));
/***/ }),
/***/ "./DeviceInput/InputDevices/deviceSourceManager.ts":
/*!*********************************************************!*\
!*** ./DeviceInput/InputDevices/deviceSourceManager.ts ***!
\*********************************************************/
/*! exports provided: DeviceSource, DeviceSourceManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceSource", function() { return DeviceSource; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceSourceManager", function() { return DeviceSourceManager; });
/* harmony import */ var _deviceInputSystem__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../deviceInputSystem */ "./DeviceInput/deviceInputSystem.ts");
/* harmony import */ var _deviceEnums__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./deviceEnums */ "./DeviceInput/InputDevices/deviceEnums.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/**
* Class that handles all input for a specific device
*/
var DeviceSource = /** @class */ (function () {
/**
* Default Constructor
* @param deviceInputSystem Reference to DeviceInputSystem
* @param deviceType Type of device
* @param deviceSlot "Slot" or index that device is referenced in
*/
function DeviceSource(deviceInputSystem,
/** Type of device */
deviceType,
/** "Slot" or index that device is referenced in */
deviceSlot) {
if (deviceSlot === void 0) { deviceSlot = 0; }
this.deviceType = deviceType;
this.deviceSlot = deviceSlot;
// Public Members
/**
* Observable to handle device input changes per device
*/
this.onInputChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
this._deviceInputSystem = deviceInputSystem;
}
/**
* Get input for specific input
* @param inputIndex index of specific input on device
* @returns Input value from DeviceInputSystem
*/
DeviceSource.prototype.getInput = function (inputIndex) {
return this._deviceInputSystem.pollInput(this.deviceType, this.deviceSlot, inputIndex);
};
return DeviceSource;
}());
/**
* Class to keep track of devices
*/
var DeviceSourceManager = /** @class */ (function () {
/**
* Default Constructor
* @param engine engine to pull input element from
*/
function DeviceSourceManager(engine) {
var _this = this;
// Public Members
/**
* Observable to be triggered when before a device is connected
*/
this.onBeforeDeviceConnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Observable to be triggered when before a device is disconnected
*/
this.onBeforeDeviceDisconnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Observable to be triggered when after a device is connected
*/
this.onAfterDeviceConnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Observable to be triggered when after a device is disconnected
*/
this.onAfterDeviceDisconnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
var numberOfDeviceTypes = Object.keys(_deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"]).length / 2;
this._devices = new Array(numberOfDeviceTypes);
this._firstDevice = new Array(numberOfDeviceTypes);
this._deviceInputSystem = _deviceInputSystem__WEBPACK_IMPORTED_MODULE_0__["DeviceInputSystem"].Create(engine);
this._deviceInputSystem.onDeviceConnected = function (deviceType, deviceSlot) {
_this.onBeforeDeviceConnectedObservable.notifyObservers({ deviceType: deviceType, deviceSlot: deviceSlot });
_this._addDevice(deviceType, deviceSlot);
_this.onAfterDeviceConnectedObservable.notifyObservers({ deviceType: deviceType, deviceSlot: deviceSlot });
};
this._deviceInputSystem.onDeviceDisconnected = function (deviceType, deviceSlot) {
_this.onBeforeDeviceDisconnectedObservable.notifyObservers({ deviceType: deviceType, deviceSlot: deviceSlot });
_this._removeDevice(deviceType, deviceSlot);
_this.onAfterDeviceDisconnectedObservable.notifyObservers({ deviceType: deviceType, deviceSlot: deviceSlot });
};
if (!this._deviceInputSystem.onInputChanged) {
this._deviceInputSystem.onInputChanged = function (deviceType, deviceSlot, inputIndex, previousState, currentState) {
var _a;
(_a = _this.getDeviceSource(deviceType, deviceSlot)) === null || _a === void 0 ? void 0 : _a.onInputChangedObservable.notifyObservers({ inputIndex: inputIndex, previousState: previousState, currentState: currentState });
};
}
}
// Public Functions
/**
* Gets a DeviceSource, given a type and slot
* @param deviceType Enum specifying device type
* @param deviceSlot "Slot" or index that device is referenced in
* @returns DeviceSource object
*/
DeviceSourceManager.prototype.getDeviceSource = function (deviceType, deviceSlot) {
if (deviceSlot === undefined) {
if (this._firstDevice[deviceType] === undefined) {
return null;
}
deviceSlot = this._firstDevice[deviceType];
}
if (!this._devices[deviceType] || this._devices[deviceType][deviceSlot] === undefined) {
return null;
}
return this._devices[deviceType][deviceSlot];
};
/**
* Gets an array of DeviceSource objects for a given device type
* @param deviceType Enum specifying device type
* @returns Array of DeviceSource objects
*/
DeviceSourceManager.prototype.getDeviceSources = function (deviceType) {
return this._devices[deviceType].filter(function (source) { return !!source; });
};
/**
* Dispose of DeviceInputSystem and other parts
*/
DeviceSourceManager.prototype.dispose = function () {
this.onBeforeDeviceConnectedObservable.clear();
this.onBeforeDeviceDisconnectedObservable.clear();
this.onAfterDeviceConnectedObservable.clear();
this.onAfterDeviceDisconnectedObservable.clear();
this._deviceInputSystem.dispose();
};
// Private Functions
/**
* Function to add device name to device list
* @param deviceType Enum specifying device type
* @param deviceSlot "Slot" or index that device is referenced in
*/
DeviceSourceManager.prototype._addDevice = function (deviceType, deviceSlot) {
if (!this._devices[deviceType]) {
this._devices[deviceType] = new Array();
}
this._devices[deviceType][deviceSlot] = new DeviceSource(this._deviceInputSystem, deviceType, deviceSlot);
this._updateFirstDevices(deviceType);
};
/**
* Function to remove device name to device list
* @param deviceType Enum specifying device type
* @param deviceSlot "Slot" or index that device is referenced in
*/
DeviceSourceManager.prototype._removeDevice = function (deviceType, deviceSlot) {
delete this._devices[deviceType][deviceSlot];
this._updateFirstDevices(deviceType);
};
/**
* Updates array storing first connected device of each type
* @param type Type of Device
*/
DeviceSourceManager.prototype._updateFirstDevices = function (type) {
switch (type) {
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].Keyboard:
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].Mouse:
this._firstDevice[type] = 0;
break;
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].Touch:
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].DualShock:
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].Xbox:
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].Switch:
case _deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"].Generic:
var devices = this._devices[type];
delete this._firstDevice[type];
for (var i = 0; i < devices.length; i++) {
if (devices[i]) {
this._firstDevice[type] = i;
break;
}
}
break;
}
};
return DeviceSourceManager;
}());
/***/ }),
/***/ "./DeviceInput/InputDevices/deviceTypes.ts":
/*!*************************************************!*\
!*** ./DeviceInput/InputDevices/deviceTypes.ts ***!
\*************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./DeviceInput/deviceInputSystem.ts":
/*!******************************************!*\
!*** ./DeviceInput/deviceInputSystem.ts ***!
\******************************************/
/*! exports provided: DeviceInputSystem */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeviceInputSystem", function() { return DeviceInputSystem; });
/* harmony import */ var _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./InputDevices/deviceEnums */ "./DeviceInput/InputDevices/deviceEnums.ts");
/**
* This class will take all inputs from Keyboard, Pointer, and
* any Gamepads and provide a polling system that all devices
* will use. This class assumes that there will only be one
* pointer device and one keyboard.
*/
var DeviceInputSystem = /** @class */ (function () {
function DeviceInputSystem(engine) {
/**
* Callback to be triggered when a device is connected
*/
this.onDeviceConnected = function () { };
/**
* Callback to be triggered when a device is disconnected
*/
this.onDeviceDisconnected = function () { };
// Private Members
this._inputs = [];
this._keyboardActive = false;
this._pointerActive = false;
this._keyboardDownEvent = function (evt) { };
this._keyboardUpEvent = function (evt) { };
this._pointerMoveEvent = function (evt) { };
this._pointerDownEvent = function (evt) { };
this._pointerUpEvent = function (evt) { };
this._gamepadConnectedEvent = function (evt) { };
this._gamepadDisconnectedEvent = function (evt) { };
var inputElement = engine.getInputElement();
if (inputElement) {
this._elementToAttachTo = inputElement;
this._handleKeyActions();
this._handlePointerActions();
this._handleGamepadActions();
}
}
/**
* Creates a new DeviceInputSystem instance
* @param engine Engine to pull input element from
* @returns The new instance
*/
DeviceInputSystem.Create = function (engine) {
// If running in Babylon Native, then defer to the native input system, which has the same public contract
if (typeof _native !== 'undefined' && _native.DeviceInputSystem) {
return new _native.DeviceInputSystem(engine);
}
return new DeviceInputSystem(engine);
};
// Public functions
/**
* Checks for current device input value, given an id and input index
* @param deviceName Id of connected device
* @param inputIndex Index of device input
* @returns Current value of input
*/
/**
* Checks for current device input value, given an id and input index. Throws exception if requested device not initialized.
* @param deviceType Enum specifiying device type
* @param deviceSlot "Slot" or index that device is referenced in
* @param inputIndex Id of input to be checked
* @returns Current value of input
*/
DeviceInputSystem.prototype.pollInput = function (deviceType, deviceSlot, inputIndex) {
var device = this._inputs[deviceType][deviceSlot];
if (!device) {
throw "Unable to find device " + _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"][deviceType];
}
this._updateDevice(deviceType, deviceSlot, inputIndex);
if (device[inputIndex] === undefined) {
throw "Unable to find input " + inputIndex + " for device " + _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"][deviceType] + " in slot " + deviceSlot;
}
return device[inputIndex];
};
/**
* Dispose of all the eventlisteners
*/
DeviceInputSystem.prototype.dispose = function () {
// Keyboard Events
if (this._keyboardActive) {
window.removeEventListener("keydown", this._keyboardDownEvent);
window.removeEventListener("keyup", this._keyboardUpEvent);
}
// Pointer Events
if (this._pointerActive) {
this._elementToAttachTo.removeEventListener("pointermove", this._pointerMoveEvent);
this._elementToAttachTo.removeEventListener("pointerdown", this._pointerDownEvent);
this._elementToAttachTo.removeEventListener("pointerup", this._pointerUpEvent);
}
// Gamepad Events
window.removeEventListener("gamepadconnected", this._gamepadConnectedEvent);
window.removeEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent);
};
// Private functions
/**
* Add device and inputs to device array
* @param deviceType Enum specifiying device type
* @param deviceSlot "Slot" or index that device is referenced in
* @param numberOfInputs Number of input entries to create for given device
*/
DeviceInputSystem.prototype._registerDevice = function (deviceType, deviceSlot, numberOfInputs) {
if (!this._inputs[deviceType]) {
this._inputs[deviceType] = [];
}
if (!this._inputs[deviceType][deviceSlot]) {
var device = new Array(numberOfInputs);
for (var i = 0; i < numberOfInputs; i++) {
device[i] = 0; /* set device input as unpressed */
}
this._inputs[deviceType][deviceSlot] = device;
this.onDeviceConnected(deviceType, deviceSlot);
}
};
/**
* Given a specific device name, remove that device from the device map
* @param deviceType Enum specifiying device type
* @param deviceSlot "Slot" or index that device is referenced in
*/
DeviceInputSystem.prototype._unregisterDevice = function (deviceType, deviceSlot) {
if (this._inputs[deviceType][deviceSlot]) {
delete this._inputs[deviceType][deviceSlot];
this.onDeviceDisconnected(deviceType, deviceSlot);
}
};
/**
* Handle all actions that come from keyboard interaction
*/
DeviceInputSystem.prototype._handleKeyActions = function () {
var _this = this;
this._keyboardDownEvent = (function (evt) {
if (!_this._keyboardActive) {
_this._keyboardActive = true;
_this._registerDevice(_InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Keyboard, 0, DeviceInputSystem._MAX_KEYCODES);
}
var kbKey = _this._inputs[_InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Keyboard][0];
if (kbKey) {
if (_this.onInputChanged) {
_this.onInputChanged(_InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Keyboard, 0, evt.keyCode, kbKey[evt.keyCode], 1);
}
kbKey[evt.keyCode] = 1;
}
});
this._keyboardUpEvent = (function (evt) {
var kbKey = _this._inputs[_InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Keyboard][0];
if (kbKey) {
if (_this.onInputChanged) {
_this.onInputChanged(_InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Keyboard, 0, evt.keyCode, kbKey[evt.keyCode], 0);
}
kbKey[evt.keyCode] = 0;
}
});
window.addEventListener("keydown", this._keyboardDownEvent);
window.addEventListener("keyup", this._keyboardUpEvent);
};
/**
* Handle all actions that come from pointer interaction
*/
DeviceInputSystem.prototype._handlePointerActions = function () {
var _this = this;
this._pointerMoveEvent = (function (evt) {
var deviceType = (evt.pointerType == "mouse") ? _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Mouse : _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Touch;
var deviceSlot = (evt.pointerType == "mouse") ? 0 : evt.pointerId;
if (!_this._inputs[deviceType]) {
_this._inputs[deviceType] = [];
}
if (!_this._inputs[deviceType][deviceSlot]) {
_this._pointerActive = true;
_this._registerDevice(deviceType, deviceSlot, DeviceInputSystem._MAX_POINTER_INPUTS);
var pointer_1 = _this._inputs[deviceType][deviceSlot]; /* initalize our pointer position immediately after registration */
pointer_1[0] = evt.clientX;
pointer_1[1] = evt.clientY;
}
var pointer = _this._inputs[deviceType][deviceSlot];
if (pointer) {
if (_this.onInputChanged) {
_this.onInputChanged(deviceType, deviceSlot, 0, pointer[0], evt.clientX);
_this.onInputChanged(deviceType, deviceSlot, 1, pointer[1], evt.clientY);
}
pointer[0] = evt.clientX;
pointer[1] = evt.clientY;
}
});
this._pointerDownEvent = (function (evt) {
var deviceType = (evt.pointerType == "mouse") ? _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Mouse : _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Touch;
var deviceSlot = (evt.pointerType == "mouse") ? 0 : evt.pointerId;
if (!_this._inputs[deviceType]) {
_this._inputs[deviceType] = [];
}
if (!_this._inputs[deviceType][deviceSlot]) {
_this._pointerActive = true;
_this._registerDevice(deviceType, deviceSlot, DeviceInputSystem._MAX_POINTER_INPUTS);
var pointer_2 = _this._inputs[deviceType][deviceSlot]; /* initalize our pointer position immediately after registration */
pointer_2[0] = evt.clientX;
pointer_2[1] = evt.clientY;
}
var pointer = _this._inputs[deviceType][deviceSlot];
if (pointer) {
if (_this.onInputChanged) {
_this.onInputChanged(deviceType, deviceSlot, 0, pointer[0], evt.clientX);
_this.onInputChanged(deviceType, deviceSlot, 1, pointer[1], evt.clientY);
_this.onInputChanged(deviceType, deviceSlot, evt.button + 2, pointer[evt.button + 2], 1);
}
pointer[0] = evt.clientX;
pointer[1] = evt.clientY;
pointer[evt.button + 2] = 1;
}
});
this._pointerUpEvent = (function (evt) {
var deviceType = (evt.pointerType == "mouse") ? _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Mouse : _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Touch;
var deviceSlot = (evt.pointerType == "mouse") ? 0 : evt.pointerId;
var pointer = _this._inputs[deviceType][deviceSlot];
if (pointer) {
if (_this.onInputChanged) {
_this.onInputChanged(deviceType, deviceSlot, evt.button + 2, pointer[evt.button + 2], 0);
}
pointer[evt.button + 2] = 0;
}
// We don't want to unregister the mouse because we may miss input data when a mouse is moving after a click
if (evt.pointerType != "mouse") {
_this._unregisterDevice(deviceType, deviceSlot);
}
});
this._elementToAttachTo.addEventListener("pointermove", this._pointerMoveEvent);
this._elementToAttachTo.addEventListener("pointerdown", this._pointerDownEvent);
this._elementToAttachTo.addEventListener("pointerup", this._pointerUpEvent);
};
/**
* Handle all actions that come from gamepad interaction
*/
DeviceInputSystem.prototype._handleGamepadActions = function () {
var _this = this;
this._gamepadConnectedEvent = (function (evt) {
var deviceType = _this._getGamepadDeviceType(evt.gamepad.id);
var deviceSlot = evt.gamepad.index;
_this._registerDevice(deviceType, deviceSlot, evt.gamepad.buttons.length + evt.gamepad.axes.length);
_this._gamepads = _this._gamepads || new Array(evt.gamepad.index + 1);
_this._gamepads[deviceSlot] = deviceType;
});
this._gamepadDisconnectedEvent = (function (evt) {
if (_this._gamepads) {
var deviceType = _this._getGamepadDeviceType(evt.gamepad.id);
var deviceSlot = evt.gamepad.index;
_this._unregisterDevice(deviceType, deviceSlot);
delete _this._gamepads[deviceSlot];
}
});
window.addEventListener("gamepadconnected", this._gamepadConnectedEvent);
window.addEventListener("gamepaddisconnected", this._gamepadDisconnectedEvent);
};
/**
* Update all non-event based devices with each frame
* @param deviceType Enum specifiying device type
* @param deviceSlot "Slot" or index that device is referenced in
* @param inputIndex Id of input to be checked
*/
DeviceInputSystem.prototype._updateDevice = function (deviceType, deviceSlot, inputIndex) {
// Gamepads
var gp = navigator.getGamepads()[deviceSlot];
if (gp && deviceType == this._gamepads[deviceSlot]) {
var device = this._inputs[deviceType][deviceSlot];
if (inputIndex >= gp.buttons.length) {
device[inputIndex] = gp.axes[inputIndex - gp.buttons.length].valueOf();
}
else {
device[inputIndex] = gp.buttons[inputIndex].value;
}
}
};
/**
* Gets DeviceType from the device name
* @param deviceName Name of Device from DeviceInputSystem
* @returns DeviceType enum value
*/
DeviceInputSystem.prototype._getGamepadDeviceType = function (deviceName) {
if (deviceName.indexOf("054c") !== -1) { // DualShock 4 Gamepad
return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].DualShock;
}
else if (deviceName.indexOf("Xbox One") !== -1 || deviceName.search("Xbox 360") !== -1 || deviceName.search("xinput") !== -1) { // Xbox Gamepad
return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Xbox;
}
else if (deviceName.indexOf("057e") !== -1) { // Switch Gamepad
return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Switch;
}
return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_0__["DeviceType"].Generic;
};
DeviceInputSystem._MAX_KEYCODES = 255;
DeviceInputSystem._MAX_POINTER_INPUTS = 7;
return DeviceInputSystem;
}());
/***/ }),
/***/ "./DeviceInput/index.ts":
/*!******************************!*\
!*** ./DeviceInput/index.ts ***!
\******************************/
/*! exports provided: DeviceInputSystem, DeviceType, PointerInput, DualShockInput, XboxInput, SwitchInput, DeviceSource, DeviceSourceManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _deviceInputSystem__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./deviceInputSystem */ "./DeviceInput/deviceInputSystem.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceInputSystem", function() { return _deviceInputSystem__WEBPACK_IMPORTED_MODULE_0__["DeviceInputSystem"]; });
/* harmony import */ var _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./InputDevices/deviceEnums */ "./DeviceInput/InputDevices/deviceEnums.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceType", function() { return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DeviceType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInput", function() { return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_1__["PointerInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockInput", function() { return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_1__["DualShockInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "XboxInput", function() { return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_1__["XboxInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchInput", function() { return _InputDevices_deviceEnums__WEBPACK_IMPORTED_MODULE_1__["SwitchInput"]; });
/* harmony import */ var _InputDevices_deviceTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./InputDevices/deviceTypes */ "./DeviceInput/InputDevices/deviceTypes.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _InputDevices_deviceSourceManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./InputDevices/deviceSourceManager */ "./DeviceInput/InputDevices/deviceSourceManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceSource", function() { return _InputDevices_deviceSourceManager__WEBPACK_IMPORTED_MODULE_3__["DeviceSource"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceSourceManager", function() { return _InputDevices_deviceSourceManager__WEBPACK_IMPORTED_MODULE_3__["DeviceSourceManager"]; });
/***/ }),
/***/ "./Engines/Extensions/engine.alpha.ts":
/*!********************************************!*\
!*** ./Engines/Extensions/engine.alpha.ts ***!
\********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../constants */ "./Engines/constants.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.setAlphaConstants = function (r, g, b, a) {
this._alphaState.setAlphaBlendConstants(r, g, b, a);
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.setAlphaMode = function (mode, noDepthWriteChange) {
if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
if (this._alphaMode === mode) {
return;
}
switch (mode) {
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_DISABLE:
this._alphaState.alphaBlend = false;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_PREMULTIPLIED:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_COMBINE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_ONEONE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_ADD:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_SUBTRACT:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_MULTIPLY:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_MAXIMIZED:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_INTERPOLATE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_SCREENMODE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_ONEONE_ONEONE:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_ALPHATOCOLOR:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ZERO);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_REVERSEONEMINUS:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE_MINUS_DST_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_SRC_DSTONEMINUSSRCALPHA:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_ONEONE_ONEZERO:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ONE, this._gl.ZERO);
this._alphaState.alphaBlend = true;
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EXCLUSION:
this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE_MINUS_DST_COLOR, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ZERO, this._gl.ONE);
this._alphaState.alphaBlend = true;
break;
}
if (!noDepthWriteChange) {
this.depthCullingState.depthMask = (mode === _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_DISABLE);
}
this._alphaMode = mode;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.getAlphaMode = function () {
return this._alphaMode;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.setAlphaEquation = function (equation) {
if (this._alphaEquation === equation) {
return;
}
switch (equation) {
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EQUATION_ADD:
this._alphaState.setAlphaEquationParameters(this._gl.FUNC_ADD, this._gl.FUNC_ADD);
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EQUATION_SUBSTRACT:
this._alphaState.setAlphaEquationParameters(this._gl.FUNC_SUBTRACT, this._gl.FUNC_SUBTRACT);
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EQUATION_REVERSE_SUBTRACT:
this._alphaState.setAlphaEquationParameters(this._gl.FUNC_REVERSE_SUBTRACT, this._gl.FUNC_REVERSE_SUBTRACT);
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EQUATION_MAX:
this._alphaState.setAlphaEquationParameters(this._gl.MAX, this._gl.MAX);
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EQUATION_MIN:
this._alphaState.setAlphaEquationParameters(this._gl.MIN, this._gl.MIN);
break;
case _constants__WEBPACK_IMPORTED_MODULE_1__["Constants"].ALPHA_EQUATION_DARKEN:
this._alphaState.setAlphaEquationParameters(this._gl.MIN, this._gl.FUNC_ADD);
break;
}
this._alphaEquation = equation;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.getAlphaEquation = function () {
return this._alphaEquation;
};
/***/ }),
/***/ "./Engines/Extensions/engine.cubeTexture.ts":
/*!**************************************************!*\
!*** ./Engines/Extensions/engine.cubeTexture.ts ***!
\**************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_fileTools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/fileTools */ "./Misc/fileTools.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype._createDepthStencilCubeTexture = function (size, options) {
var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTextureSource"].Unknown);
internalTexture.isCube = true;
if (this.webGLVersion === 1) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Error("Depth cube texture is not supported by WebGL 1.");
return internalTexture;
}
var internalOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
var gl = this._gl;
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
// Create the depth/stencil buffer
for (var face = 0; face < 6; face++) {
if (internalOptions.generateStencil) {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH24_STENCIL8, size, size, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
}
else {
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
}
}
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
return internalTexture;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype._partialLoadFile = function (url, index, loadedFiles, onfinish, onErrorCallBack) {
if (onErrorCallBack === void 0) { onErrorCallBack = null; }
var onload = function (data) {
loadedFiles[index] = data;
loadedFiles._internalCount++;
if (loadedFiles._internalCount === 6) {
onfinish(loadedFiles);
}
};
var onerror = function (request, exception) {
if (onErrorCallBack && request) {
onErrorCallBack(request.status + " " + request.statusText, exception);
}
};
this._loadFile(url, onload, undefined, undefined, true, onerror);
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
if (onError === void 0) { onError = null; }
var loadedFiles = [];
loadedFiles._internalCount = 0;
for (var index = 0; index < 6; index++) {
this._partialLoadFile(files[index], index, loadedFiles, onfinish, onError);
}
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype._cascadeLoadImgs = function (scene, onfinish, files, onError, mimeType) {
if (onError === void 0) { onError = null; }
var loadedImages = [];
loadedImages._internalCount = 0;
for (var index = 0; index < 6; index++) {
this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError, mimeType);
}
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack, mimeType) {
if (onErrorCallBack === void 0) { onErrorCallBack = null; }
var img;
var onload = function () {
if (img) {
loadedImages[index] = img;
loadedImages._internalCount++;
if (scene) {
scene._removePendingData(img);
}
}
if (loadedImages._internalCount === 6) {
onfinish(loadedImages);
}
};
var onerror = function (message, exception) {
if (scene) {
scene._removePendingData(img);
}
if (onErrorCallBack) {
onErrorCallBack(message, exception);
}
};
img = _Misc_fileTools__WEBPACK_IMPORTED_MODULE_4__["FileTools"].LoadImage(url, onload, onerror, scene ? scene.offlineProvider : null, mimeType);
if (scene && img) {
scene._addPendingData(img);
}
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype._setCubeMapTextureParams = function (loadMipmap) {
var gl = this._gl;
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
var _this = this;
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
if (createPolynomials === void 0) { createPolynomials = false; }
if (lodScale === void 0) { lodScale = 0; }
if (lodOffset === void 0) { lodOffset = 0; }
if (fallback === void 0) { fallback = null; }
var gl = this._gl;
var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTextureSource"].Cube);
texture.isCube = true;
texture.url = rootUrl;
texture.generateMipMaps = !noMipmap;
texture._lodGenerationScale = lodScale;
texture._lodGenerationOffset = lodOffset;
if (!this._doNotHandleContextLost) {
texture._extension = forcedExtension;
texture._files = files;
}
var originalRootUrl = rootUrl;
if (this._transformTextureUrl && !fallback) {
rootUrl = this._transformTextureUrl(rootUrl);
}
var lastDot = rootUrl.lastIndexOf('.');
var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
var loader = null;
for (var _i = 0, _a = _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"]._TextureLoaders; _i < _a.length; _i++) {
var availableLoader = _a[_i];
if (availableLoader.canLoad(extension)) {
loader = availableLoader;
break;
}
}
var onInternalError = function (request, exception) {
if (rootUrl === originalRootUrl) {
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
}
else {
// fall back to the original url if the transformed url fails to load
_Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("Failed to load " + rootUrl + ", falling back to the " + originalRootUrl);
_this.createCubeTexture(originalRootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, texture);
}
};
if (loader) {
var onloaddata_1 = function (data) {
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
};
if (files && files.length === 6) {
if (loader.supportCascades) {
this._cascadeLoadFiles(scene, function (images) { return onloaddata_1(images.map(function (image) { return new Uint8Array(image); })); }, files, onError);
}
else {
if (onError) {
onError("Textures type does not support cascades.");
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("Texture loader does not support cascades.");
}
}
}
else {
this._loadFile(rootUrl, function (data) { return onloaddata_1(new Uint8Array(data)); }, undefined, undefined, true, onInternalError);
}
}
else {
if (!files) {
throw new Error("Cannot load cubemap because files were not defined");
}
this._cascadeLoadImgs(scene, function (imgs) {
var width = _this.needPOTTextures ? _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_1__["ThinEngine"].GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
var height = width;
var faces = [
gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
];
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
_this._unpackFlipY(false);
var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
for (var index = 0; index < faces.length; index++) {
if (imgs[index].width !== width || imgs[index].height !== height) {
_this._prepareWorkingCanvas();
if (!_this._workingCanvas || !_this._workingContext) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("Cannot create canvas to resize texture.");
return;
}
_this._workingCanvas.width = width;
_this._workingCanvas.height = height;
_this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
}
else {
gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, imgs[index]);
}
}
if (!noMipmap) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
_this._setCubeMapTextureParams(!noMipmap);
texture.width = width;
texture.height = height;
texture.isReady = true;
if (format) {
texture.format = format;
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}, files, onError);
}
this._internalTexturesCache.push(texture);
return texture;
};
/***/ }),
/***/ "./Engines/Extensions/engine.dynamicBuffer.ts":
/*!****************************************************!*\
!*** ./Engines/Extensions/engine.dynamicBuffer.ts ***!
\****************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
if (offset === void 0) { offset = 0; }
// Force cache update
this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
this.bindIndexBuffer(indexBuffer);
var arrayBuffer;
if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
arrayBuffer = indices;
}
else {
arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
}
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
this._resetIndexBufferBinding();
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
this.bindArrayBuffer(vertexBuffer);
if (byteOffset === undefined) {
byteOffset = 0;
}
var dataLength = data.length || data.byteLength;
if (byteLength === undefined || byteLength >= dataLength && byteOffset === 0) {
if (data instanceof Array) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
}
else {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
}
}
else {
if (data instanceof Array) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
}
else {
if (data instanceof ArrayBuffer) {
data = new Uint8Array(data, byteOffset, byteLength);
}
else {
data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
}
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
}
}
this._resetVertexBufferBinding();
};
/***/ }),
/***/ "./Engines/Extensions/engine.dynamicTexture.ts":
/*!*****************************************************!*\
!*** ./Engines/Extensions/engine.dynamicTexture.ts ***!
\*****************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTextureSource"].Dynamic);
texture.baseWidth = width;
texture.baseHeight = height;
if (generateMipMaps) {
width = this.needPOTTextures ? _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
height = this.needPOTTextures ? _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
}
// this.resetTextureCache();
texture.width = width;
texture.height = height;
texture.isReady = false;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
this.updateTextureSamplingMode(samplingMode, texture);
this._internalTexturesCache.push(texture);
return texture;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format, forceBindTexture) {
if (premulAlpha === void 0) { premulAlpha = false; }
if (forceBindTexture === void 0) { forceBindTexture = false; }
if (!texture) {
return;
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true, forceBindTexture);
this._unpackFlipY(invertY);
if (premulAlpha) {
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
}
var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
if (premulAlpha) {
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
}
texture.isReady = true;
};
/***/ }),
/***/ "./Engines/Extensions/engine.multiRender.ts":
/*!**************************************************!*\
!*** ./Engines/Extensions/engine.multiRender.ts ***!
\**************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../constants */ "./Engines/constants.ts");
/* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../thinEngine */ "./Engines/thinEngine.ts");
_thinEngine__WEBPACK_IMPORTED_MODULE_3__["ThinEngine"].prototype.bindAttachments = function (attachments) {
var gl = this._gl;
gl.drawBuffers(attachments);
};
_thinEngine__WEBPACK_IMPORTED_MODULE_3__["ThinEngine"].prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
this._currentRenderTarget = null;
// If MSAA, we need to bitblt back to main texture
var gl = this._gl;
var attachments = textures[0]._attachments;
var count = attachments.length;
if (textures[0]._MSAAFramebuffer) {
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
for (var i = 0; i < count; i++) {
var texture = textures[i];
for (var j = 0; j < count; j++) {
attachments[j] = gl.NONE;
}
attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
gl.readBuffer(attachments[i]);
gl.drawBuffers(attachments);
gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
}
for (var i = 0; i < count; i++) {
attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
}
gl.drawBuffers(attachments);
}
for (var i = 0; i < count; i++) {
var texture = textures[i];
if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
gl.generateMipmap(gl.TEXTURE_2D);
this._bindTextureDirectly(gl.TEXTURE_2D, null);
}
}
if (onBeforeUnbind) {
if (textures[0]._MSAAFramebuffer) {
// Bind the correct framebuffer
this._bindUnboundFramebuffer(textures[0]._framebuffer);
}
onBeforeUnbind();
}
this._bindUnboundFramebuffer(null);
};
_thinEngine__WEBPACK_IMPORTED_MODULE_3__["ThinEngine"].prototype.createMultipleRenderTarget = function (size, options) {
var generateMipMaps = false;
var generateDepthBuffer = true;
var generateStencilBuffer = false;
var generateDepthTexture = false;
var textureCount = 1;
var defaultType = _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT;
var defaultSamplingMode = _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE;
var types = new Array();
var samplingModes = new Array();
if (options !== undefined) {
generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
textureCount = options.textureCount || 1;
if (options.types) {
types = options.types;
}
if (options.samplingModes) {
samplingModes = options.samplingModes;
}
}
var gl = this._gl;
// Create the framebuffer
var framebuffer = gl.createFramebuffer();
this._bindUnboundFramebuffer(framebuffer);
var width = size.width || size;
var height = size.height || size;
var textures = [];
var attachments = [];
var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
for (var i = 0; i < textureCount; i++) {
var samplingMode = samplingModes[i] || defaultSamplingMode;
var type = types[i] || defaultType;
if (type === _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
// if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
else if (type === _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
samplingMode = _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
if (type === _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
type = _constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_INT;
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"].MultiRenderTarget);
var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
textures.push(texture);
attachments.push(attachment);
gl.activeTexture(gl["TEXTURE" + i]);
gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
// Unbind
this._bindTextureDirectly(gl.TEXTURE_2D, null);
texture._framebuffer = framebuffer;
texture._depthStencilBuffer = depthStencilBuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.type = type;
texture._generateDepthBuffer = generateDepthBuffer;
texture._generateStencilBuffer = generateStencilBuffer;
texture._attachments = attachments;
texture._textureArray = textures;
this._internalTexturesCache.push(texture);
}
if (generateDepthTexture && this._caps.depthTextureExtension) {
// Depth texture
var depthTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"].MultiRenderTarget);
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texImage2D(gl.TEXTURE_2D, 0, this.webGLVersion < 2 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
depthTexture._framebuffer = framebuffer;
depthTexture.baseWidth = width;
depthTexture.baseHeight = height;
depthTexture.width = width;
depthTexture.height = height;
depthTexture.isReady = true;
depthTexture.samples = 1;
depthTexture.generateMipMaps = generateMipMaps;
depthTexture.samplingMode = gl.NEAREST;
depthTexture._generateDepthBuffer = generateDepthBuffer;
depthTexture._generateStencilBuffer = generateStencilBuffer;
textures.push(depthTexture);
this._internalTexturesCache.push(depthTexture);
}
gl.drawBuffers(attachments);
this._bindUnboundFramebuffer(null);
this.resetTextureCache();
return textures;
};
_thinEngine__WEBPACK_IMPORTED_MODULE_3__["ThinEngine"].prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
if (this.webGLVersion < 2 || !textures) {
return 1;
}
if (textures[0].samples === samples) {
return samples;
}
var count = textures[0]._attachments.length;
if (count === 0) {
return 1;
}
var gl = this._gl;
samples = Math.min(samples, this.getCaps().maxMSAASamples);
// Dispose previous render buffers
if (textures[0]._depthStencilBuffer) {
gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
textures[0]._depthStencilBuffer = null;
}
if (textures[0]._MSAAFramebuffer) {
gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
textures[0]._MSAAFramebuffer = null;
}
for (var i = 0; i < count; i++) {
if (textures[i]._MSAARenderBuffer) {
gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
textures[i]._MSAARenderBuffer = null;
}
}
if (samples > 1 && gl.renderbufferStorageMultisample) {
var framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
this._bindUnboundFramebuffer(framebuffer);
var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
var attachments = [];
for (var i = 0; i < count; i++) {
var texture = textures[i];
var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
var colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
texture._MSAAFramebuffer = framebuffer;
texture._MSAARenderBuffer = colorRenderbuffer;
texture.samples = samples;
texture._depthStencilBuffer = depthStencilBuffer;
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
attachments.push(attachment);
}
gl.drawBuffers(attachments);
}
else {
this._bindUnboundFramebuffer(textures[0]._framebuffer);
}
this._bindUnboundFramebuffer(null);
return samples;
};
/***/ }),
/***/ "./Engines/Extensions/engine.multiview.ts":
/*!************************************************!*\
!*** ./Engines/Extensions/engine.multiview.ts ***!
\************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../scene */ "./scene.ts");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/uniformBuffer */ "./Materials/uniformBuffer.ts");
/* harmony import */ var _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/Textures/MultiviewRenderTarget */ "./Materials/Textures/MultiviewRenderTarget.ts");
/* harmony import */ var _Maths_math_frustum__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Maths/math.frustum */ "./Maths/math.frustum.ts");
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.createMultiviewRenderTargetTexture = function (width, height) {
var gl = this._gl;
if (!this.getCaps().multiview) {
throw "Multiview is not supported";
}
var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_3__["InternalTextureSource"].Unknown, true);
internalTexture.width = width;
internalTexture.height = height;
internalTexture._framebuffer = gl.createFramebuffer();
internalTexture._colorTextureArray = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D_ARRAY, internalTexture._colorTextureArray);
gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.RGBA8, width, height, 2);
internalTexture._depthStencilTextureArray = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D_ARRAY, internalTexture._depthStencilTextureArray);
gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 1, gl.DEPTH32F_STENCIL8, width, height, 2);
internalTexture.isReady = true;
return internalTexture;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.bindMultiviewFramebuffer = function (multiviewTexture) {
var gl = this._gl;
var ext = this.getCaps().oculusMultiview || this.getCaps().multiview;
this.bindFramebuffer(multiviewTexture, undefined, undefined, undefined, true);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, multiviewTexture._framebuffer);
if (multiviewTexture._colorTextureArray && multiviewTexture._depthStencilTextureArray) {
if (this.getCaps().oculusMultiview) {
ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, multiviewTexture.samples, 0, 2);
ext.framebufferTextureMultisampleMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, multiviewTexture.samples, 0, 2);
}
else {
ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, multiviewTexture._colorTextureArray, 0, 0, 2);
ext.framebufferTextureMultiviewOVR(gl.DRAW_FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, multiviewTexture._depthStencilTextureArray, 0, 0, 2);
}
}
else {
throw "Invalid multiview frame buffer";
}
};
_Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._useMultiviewToSingleView = false;
_Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._multiviewTexture = null;
_Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].prototype._resizeOrCreateMultiviewTexture = function (width, height) {
if (!this._multiviewTexture) {
this._multiviewTexture = new _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__["MultiviewRenderTarget"](this.getScene(), { width: width, height: height });
}
else if (this._multiviewTexture.getRenderWidth() != width || this._multiviewTexture.getRenderHeight() != height) {
this._multiviewTexture.dispose();
this._multiviewTexture = new _Materials_Textures_MultiviewRenderTarget__WEBPACK_IMPORTED_MODULE_6__["MultiviewRenderTarget"](this.getScene(), { width: width, height: height });
}
};
_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._transformMatrixR = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Matrix"].Zero();
_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._multiviewSceneUbo = null;
_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._createMultiviewUbo = function () {
this._multiviewSceneUbo = new _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__["UniformBuffer"](this.getEngine(), undefined, true);
this._multiviewSceneUbo.addUniform("viewProjection", 16);
this._multiviewSceneUbo.addUniform("viewProjectionR", 16);
this._multiviewSceneUbo.addUniform("view", 16);
};
_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._updateMultiviewUbo = function (viewR, projectionR) {
if (viewR && projectionR) {
viewR.multiplyToRef(projectionR, this._transformMatrixR);
}
if (viewR && projectionR) {
viewR.multiplyToRef(projectionR, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Matrix[0]);
_Maths_math_frustum__WEBPACK_IMPORTED_MODULE_7__["Frustum"].GetRightPlaneToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["TmpVectors"].Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
}
if (this._multiviewSceneUbo) {
this._multiviewSceneUbo.updateMatrix("viewProjection", this.getTransformMatrix());
this._multiviewSceneUbo.updateMatrix("viewProjectionR", this._transformMatrixR);
this._multiviewSceneUbo.updateMatrix("view", this._viewMatrix);
this._multiviewSceneUbo.update();
}
};
_scene__WEBPACK_IMPORTED_MODULE_2__["Scene"].prototype._renderMultiviewToSingleView = function (camera) {
// Multiview is only able to be displayed directly for API's such as webXR
// This displays a multiview image by rendering to the multiview image and then
// copying the result into the sub cameras instead of rendering them and proceeding as normal from there
// Render to a multiview texture
camera._resizeOrCreateMultiviewTexture((camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.width > 0) ? camera._rigPostProcess.width : this.getEngine().getRenderWidth(true), (camera._rigPostProcess && camera._rigPostProcess && camera._rigPostProcess.height > 0) ? camera._rigPostProcess.height : this.getEngine().getRenderHeight(true));
if (!this._multiviewSceneUbo) {
this._createMultiviewUbo();
}
camera.outputRenderTarget = camera._multiviewTexture;
this._renderForCamera(camera);
camera.outputRenderTarget = null;
// Consume the multiview texture through a shader for each eye
for (var index = 0; index < camera._rigCameras.length; index++) {
var engine = this.getEngine();
this._activeCamera = camera._rigCameras[index];
engine.setViewport(this._activeCamera.viewport);
if (this.postProcessManager) {
this.postProcessManager._prepareFrame();
this.postProcessManager._finalizeFrame(this._activeCamera.isIntermediate);
}
}
};
/***/ }),
/***/ "./Engines/Extensions/engine.occlusionQuery.ts":
/*!*****************************************************!*\
!*** ./Engines/Extensions/engine.occlusionQuery.ts ***!
\*****************************************************/
/*! exports provided: _OcclusionDataStorage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _OcclusionDataStorage; });
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Instrumentation_timeToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Instrumentation/timeToken */ "./Instrumentation/timeToken.ts");
/** @hidden */
var _OcclusionDataStorage = /** @class */ (function () {
function _OcclusionDataStorage() {
/** @hidden */
this.occlusionInternalRetryCounter = 0;
/** @hidden */
this.isOcclusionQueryInProgress = false;
/** @hidden */
this.isOccluded = false;
/** @hidden */
this.occlusionRetryCount = -1;
/** @hidden */
this.occlusionType = _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_NONE;
/** @hidden */
this.occlusionQueryAlgorithmType = _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
}
return _OcclusionDataStorage;
}());
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createQuery = function () {
return this._gl.createQuery();
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.deleteQuery = function (query) {
this._gl.deleteQuery(query);
return this;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.isQueryResultAvailable = function (query) {
return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.getQueryResult = function (query) {
return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.beginOcclusionQuery = function (algorithmType, query) {
var glAlgorithm = this._getGlAlgorithmType(algorithmType);
this._gl.beginQuery(glAlgorithm, query);
return this;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endOcclusionQuery = function (algorithmType) {
var glAlgorithm = this._getGlAlgorithmType(algorithmType);
this._gl.endQuery(glAlgorithm);
return this;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._createTimeQuery = function () {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.createQueryEXT) {
return timerQuery.createQueryEXT();
}
return this.createQuery();
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._deleteTimeQuery = function (query) {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.deleteQueryEXT) {
timerQuery.deleteQueryEXT(query);
return;
}
this.deleteQuery(query);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getTimeQueryResult = function (query) {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.getQueryObjectEXT) {
return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
}
return this.getQueryResult(query);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getTimeQueryAvailability = function (query) {
var timerQuery = this.getCaps().timerQuery;
if (timerQuery.getQueryObjectEXT) {
return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
}
return this.isQueryResultAvailable(query);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.startTimeQuery = function () {
var caps = this.getCaps();
var timerQuery = caps.timerQuery;
if (!timerQuery) {
return null;
}
var token = new _Instrumentation_timeToken__WEBPACK_IMPORTED_MODULE_2__["_TimeToken"]();
this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
if (caps.canUseTimestampForTimerQuery) {
token._startTimeQuery = this._createTimeQuery();
timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
}
else {
if (this._currentNonTimestampToken) {
return this._currentNonTimestampToken;
}
token._timeElapsedQuery = this._createTimeQuery();
if (timerQuery.beginQueryEXT) {
timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
}
else {
this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
}
this._currentNonTimestampToken = token;
}
return token;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endTimeQuery = function (token) {
var caps = this.getCaps();
var timerQuery = caps.timerQuery;
if (!timerQuery || !token) {
return -1;
}
if (caps.canUseTimestampForTimerQuery) {
if (!token._startTimeQuery) {
return -1;
}
if (!token._endTimeQuery) {
token._endTimeQuery = this._createTimeQuery();
timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
}
}
else if (!token._timeElapsedQueryEnded) {
if (!token._timeElapsedQuery) {
return -1;
}
if (timerQuery.endQueryEXT) {
timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
}
else {
this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
}
token._timeElapsedQueryEnded = true;
}
var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
var available = false;
if (token._endTimeQuery) {
available = this._getTimeQueryAvailability(token._endTimeQuery);
}
else if (token._timeElapsedQuery) {
available = this._getTimeQueryAvailability(token._timeElapsedQuery);
}
if (available && !disjoint) {
var result = 0;
if (caps.canUseTimestampForTimerQuery) {
if (!token._startTimeQuery || !token._endTimeQuery) {
return -1;
}
var timeStart = this._getTimeQueryResult(token._startTimeQuery);
var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
result = timeEnd - timeStart;
this._deleteTimeQuery(token._startTimeQuery);
this._deleteTimeQuery(token._endTimeQuery);
token._startTimeQuery = null;
token._endTimeQuery = null;
}
else {
if (!token._timeElapsedQuery) {
return -1;
}
result = this._getTimeQueryResult(token._timeElapsedQuery);
this._deleteTimeQuery(token._timeElapsedQuery);
token._timeElapsedQuery = null;
token._timeElapsedQueryEnded = false;
this._currentNonTimestampToken = null;
}
return result;
}
return -1;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._getGlAlgorithmType = function (algorithmType) {
return algorithmType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
};
Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "isOcclusionQueryInProgress", {
get: function () {
return this._occlusionDataStorage.isOcclusionQueryInProgress;
},
set: function (value) {
this._occlusionDataStorage.isOcclusionQueryInProgress = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "_occlusionDataStorage", {
get: function () {
if (!this.__occlusionDataStorage) {
this.__occlusionDataStorage = new _OcclusionDataStorage();
}
return this.__occlusionDataStorage;
},
enumerable: false,
configurable: true
});
Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "isOccluded", {
get: function () {
return this._occlusionDataStorage.isOccluded;
},
set: function (value) {
this._occlusionDataStorage.isOccluded = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionQueryAlgorithmType", {
get: function () {
return this._occlusionDataStorage.occlusionQueryAlgorithmType;
},
set: function (value) {
this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionType", {
get: function () {
return this._occlusionDataStorage.occlusionType;
},
set: function (value) {
this._occlusionDataStorage.occlusionType = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype, "occlusionRetryCount", {
get: function () {
return this._occlusionDataStorage.occlusionRetryCount;
},
set: function (value) {
this._occlusionDataStorage.occlusionRetryCount = value;
},
enumerable: true,
configurable: true
});
// We also need to update AbstractMesh as there is a portion of the code there
_Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].prototype._checkOcclusionQuery = function () {
var dataStorage = this._occlusionDataStorage;
if (dataStorage.occlusionType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_NONE) {
dataStorage.isOccluded = false;
return false;
}
var engine = this.getEngine();
if (engine.webGLVersion < 2) {
dataStorage.isOccluded = false;
return false;
}
if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
dataStorage.isOccluded = false;
return false;
}
if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
if (isOcclusionQueryAvailable) {
var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
dataStorage.isOcclusionQueryInProgress = false;
dataStorage.occlusionInternalRetryCounter = 0;
dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
}
else {
dataStorage.occlusionInternalRetryCounter++;
if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
dataStorage.isOcclusionQueryInProgress = false;
dataStorage.occlusionInternalRetryCounter = 0;
// if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
// if strict continue the last state of the object.
dataStorage.isOccluded = dataStorage.occlusionType === _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_1__["AbstractMesh"].OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
}
else {
return false;
}
}
}
var scene = this.getScene();
if (scene.getBoundingBoxRenderer) {
var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
if (!this._occlusionQuery) {
this._occlusionQuery = engine.createQuery();
}
engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
this._occlusionDataStorage.isOcclusionQueryInProgress = true;
}
return dataStorage.isOccluded;
};
/***/ }),
/***/ "./Engines/Extensions/engine.rawTexture.ts":
/*!*************************************************!*\
!*** ./Engines/Extensions/engine.rawTexture.ts ***!
\*************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../constants */ "./Engines/constants.ts");
/* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../thinEngine */ "./Engines/thinEngine.ts");
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
if (compression === void 0) { compression = null; }
if (type === void 0) { type = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
if (!texture) {
return;
}
// Babylon's internalSizedFomat but gl's texImage2D internalFormat
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
// Babylon's internalFormat but gl's texImage2D format
var internalFormat = this._getInternalFormat(format);
var textureType = this._getWebGLTextureType(type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
texture.format = format;
texture.type = type;
texture.invertY = invertY;
texture._compression = compression;
}
if (texture.width % 4 !== 0) {
this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
}
if (compression && data) {
this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
}
else {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
// this.resetTextureCache();
texture.isReady = true;
};
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
if (compression === void 0) { compression = null; }
if (type === void 0) { type = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"].Raw);
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.format = format;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
texture._compression = compression;
texture.type = type;
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
}
this.updateRawTexture(texture, data, format, invertY, compression, type);
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
// Filters
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._internalTexturesCache.push(texture);
return texture;
};
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
if (compression === void 0) { compression = null; }
var gl = this._gl;
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"].CubeRaw);
texture.isCube = true;
texture.format = format;
texture.type = type;
if (!this._doNotHandleContextLost) {
texture._bufferViewArray = data;
}
var textureType = this._getWebGLTextureType(type);
var internalFormat = this._getInternalFormat(format);
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
}
// Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
generateMipMaps = false;
samplingMode = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
}
else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
generateMipMaps = false;
samplingMode = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
}
else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
generateMipMaps = false;
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Render to float textures is not supported. Mipmap generation forced to false.");
}
else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
generateMipMaps = false;
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
}
var width = size;
var height = width;
texture.width = width;
texture.height = height;
// Double check on POT to generate Mips.
var isPot = !this.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(texture.width) && _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(texture.height));
if (!isPot) {
generateMipMaps = false;
}
// Upload data if needed. The texture won't be ready until then.
if (data) {
this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
// Filters
if (data && generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
}
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
texture.generateMipMaps = generateMipMaps;
return texture;
};
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
if (compression === void 0) { compression = null; }
if (level === void 0) { level = 0; }
texture._bufferViewArray = data;
texture.format = format;
texture.type = type;
texture.invertY = invertY;
texture._compression = compression;
var gl = this._gl;
var textureType = this._getWebGLTextureType(type);
var internalFormat = this._getInternalFormat(format);
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
var needConversion = false;
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
needConversion = true;
}
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
if (texture.width % 4 !== 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
}
// Data are known to be in +X +Y +Z -X -Y -Z
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var faceData = data[faceIndex];
if (compression) {
gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
}
else {
if (needConversion) {
faceData = _convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
}
gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
}
}
var isPot = !this.needPOTTextures || (_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(texture.width) && _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].IsExponentOfTwo(texture.height));
if (isPot && texture.generateMipMaps && level === 0) {
this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
// this.resetTextureCache();
texture.isReady = true;
};
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
var _this = this;
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; }
if (invertY === void 0) { invertY = false; }
var gl = this._gl;
var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode, null);
scene === null || scene === void 0 ? void 0 : scene._addPendingData(texture);
texture.url = url;
this._internalTexturesCache.push(texture);
var onerror = function (request, exception) {
scene === null || scene === void 0 ? void 0 : scene._removePendingData(texture);
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
};
var internalCallback = function (data) {
var width = texture.width;
var faceDataArrays = callback(data);
if (!faceDataArrays) {
return;
}
if (mipmapGenerator) {
var textureType = _this._getWebGLTextureType(type);
var internalFormat = _this._getInternalFormat(format);
var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
var needConversion = false;
if (internalFormat === gl.RGB) {
internalFormat = gl.RGBA;
needConversion = true;
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
_this._unpackFlipY(false);
var mipData = mipmapGenerator(faceDataArrays);
for (var level = 0; level < mipData.length; level++) {
var mipSize = width >> level;
for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
var mipFaceData = mipData[level][faceIndex];
if (needConversion) {
mipFaceData = _convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
}
gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
}
}
_this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
}
else {
_this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
}
texture.isReady = true;
// this.resetTextureCache();
scene === null || scene === void 0 ? void 0 : scene._removePendingData(texture);
if (onLoad) {
onLoad();
}
};
this._loadFile(url, function (data) {
internalCallback(data);
}, undefined, scene === null || scene === void 0 ? void 0 : scene.offlineProvider, true, onerror);
return texture;
};
/** @hidden */
function _convertRGBtoRGBATextureData(rgbData, width, height, textureType) {
// Create new RGBA data container.
var rgbaData;
if (textureType === _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_FLOAT) {
rgbaData = new Float32Array(width * height * 4);
}
else {
rgbaData = new Uint32Array(width * height * 4);
}
// Convert each pixel.
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
var index = (y * width + x) * 3;
var newIndex = (y * width + x) * 4;
// Map Old Value to new value.
rgbaData[newIndex + 0] = rgbData[index + 0];
rgbaData[newIndex + 1] = rgbData[index + 1];
rgbaData[newIndex + 2] = rgbData[index + 2];
// Add fully opaque alpha channel.
rgbaData[newIndex + 3] = 1;
}
}
return rgbaData;
}
/**
* Create a function for createRawTexture3D/createRawTexture2DArray
* @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY
* @hidden
*/
function _makeCreateRawTextureFunction(is3D) {
return function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
if (compression === void 0) { compression = null; }
if (textureType === void 0) { textureType = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
var target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;
var source = is3D ? _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"].Raw3D : _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"].Raw2DArray;
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"](this, source);
texture.baseWidth = width;
texture.baseHeight = height;
texture.baseDepth = depth;
texture.width = width;
texture.height = height;
texture.depth = depth;
texture.format = format;
texture.type = textureType;
texture.generateMipMaps = generateMipMaps;
texture.samplingMode = samplingMode;
if (is3D) {
texture.is3D = true;
}
else {
texture.is2DArray = true;
}
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
}
if (is3D) {
this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
}
else {
this.updateRawTexture2DArray(texture, data, format, invertY, compression, textureType);
}
this._bindTextureDirectly(target, texture, true);
// Filters
var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
this._gl.texParameteri(target, this._gl.TEXTURE_MAG_FILTER, filters.mag);
this._gl.texParameteri(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
this._gl.generateMipmap(target);
}
this._bindTextureDirectly(target, null);
this._internalTexturesCache.push(texture);
return texture;
};
}
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.createRawTexture2DArray = _makeCreateRawTextureFunction(false);
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.createRawTexture3D = _makeCreateRawTextureFunction(true);
/**
* Create a function for updateRawTexture3D/updateRawTexture2DArray
* @param is3D true for TEXTURE_3D and false for TEXTURE_2D_ARRAY
* @hidden
*/
function _makeUpdateRawTextureFunction(is3D) {
return function (texture, data, format, invertY, compression, textureType) {
if (compression === void 0) { compression = null; }
if (textureType === void 0) { textureType = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
var target = is3D ? this._gl.TEXTURE_3D : this._gl.TEXTURE_2D_ARRAY;
var internalType = this._getWebGLTextureType(textureType);
var internalFormat = this._getInternalFormat(format);
var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
this._bindTextureDirectly(target, texture, true);
this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
if (!this._doNotHandleContextLost) {
texture._bufferView = data;
texture.format = format;
texture.invertY = invertY;
texture._compression = compression;
}
if (texture.width % 4 !== 0) {
this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
}
if (compression && data) {
this._gl.compressedTexImage3D(target, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
}
else {
this._gl.texImage3D(target, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(target);
}
this._bindTextureDirectly(target, null);
// this.resetTextureCache();
texture.isReady = true;
};
}
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.updateRawTexture2DArray = _makeUpdateRawTextureFunction(false);
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.updateRawTexture3D = _makeUpdateRawTextureFunction(true);
/***/ }),
/***/ "./Engines/Extensions/engine.readTexture.ts":
/*!**************************************************!*\
!*** ./Engines/Extensions/engine.readTexture.ts ***!
\**************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
if (faceIndex === void 0) { faceIndex = -1; }
if (level === void 0) { level = 0; }
if (buffer === void 0) { buffer = null; }
var gl = this._gl;
if (!gl) {
throw new Error("Engine does not have gl rendering context.");
}
if (!this._dummyFramebuffer) {
var dummy = gl.createFramebuffer();
if (!dummy) {
throw new Error("Unable to create dummy framebuffer");
}
this._dummyFramebuffer = dummy;
}
gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
if (faceIndex > -1) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
}
else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
}
var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
switch (readType) {
case gl.UNSIGNED_BYTE:
if (!buffer) {
buffer = new Uint8Array(4 * width * height);
}
readType = gl.UNSIGNED_BYTE;
break;
default:
if (!buffer) {
buffer = new Float32Array(4 * width * height);
}
readType = gl.FLOAT;
break;
}
gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
return buffer;
};
/***/ }),
/***/ "./Engines/Extensions/engine.renderTarget.ts":
/*!***************************************************!*\
!*** ./Engines/Extensions/engine.renderTarget.ts ***!
\***************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../constants */ "./Engines/constants.ts");
/* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../thinEngine */ "./Engines/thinEngine.ts");
_thinEngine__WEBPACK_IMPORTED_MODULE_5__["ThinEngine"].prototype.createRenderTargetTexture = function (size, options) {
var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__["RenderTargetCreationOptions"]();
if (options !== undefined && typeof options === "object") {
fullOptions.generateMipMaps = options.generateMipMaps;
fullOptions.generateDepthBuffer = !!options.generateDepthBuffer;
fullOptions.generateStencilBuffer = !!options.generateStencilBuffer;
fullOptions.type = options.type === undefined ? _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURETYPE_UNSIGNED_INT : options.type;
fullOptions.samplingMode = options.samplingMode === undefined ? _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
fullOptions.format = options.format === undefined ? _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTUREFORMAT_RGBA : options.format;
}
else {
fullOptions.generateMipMaps = options;
fullOptions.generateDepthBuffer = true;
fullOptions.generateStencilBuffer = false;
fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURETYPE_UNSIGNED_INT;
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE;
fullOptions.format = _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTUREFORMAT_RGBA;
}
if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
// if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
else if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_4__["Constants"].TEXTURETYPE_UNSIGNED_INT;
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
var gl = this._gl;
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTextureSource"].RenderTarget);
var width = size.width || size;
var height = size.height || size;
var layers = size.layers || 0;
var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
var target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : gl.TEXTURE_2D;
var sizedFormat = this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format);
var internalFormat = this._getInternalFormat(fullOptions.format);
var type = this._getWebGLTextureType(fullOptions.type);
// Bind
this._bindTextureDirectly(target, texture);
if (layers !== 0) {
texture.is2DArray = true;
gl.texImage3D(target, 0, sizedFormat, width, height, layers, 0, internalFormat, type, null);
}
else {
gl.texImage2D(target, 0, sizedFormat, width, height, 0, internalFormat, type, null);
}
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// MipMaps
if (fullOptions.generateMipMaps) {
this._gl.generateMipmap(target);
}
this._bindTextureDirectly(target, null);
// Create the framebuffer
var framebuffer = gl.createFramebuffer();
this._bindUnboundFramebuffer(framebuffer);
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
// No need to rebind on every frame
if (!texture.is2DArray) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
}
this._bindUnboundFramebuffer(null);
texture._framebuffer = framebuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.depth = layers;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture.format = fullOptions.format;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
this._internalTexturesCache.push(texture);
return texture;
};
_thinEngine__WEBPACK_IMPORTED_MODULE_5__["ThinEngine"].prototype.createDepthStencilTexture = function (size, options) {
if (options.isCube) {
var width = size.width || size;
return this._createDepthStencilCubeTexture(width, options);
}
else {
return this._createDepthStencilTexture(size, options);
}
};
_thinEngine__WEBPACK_IMPORTED_MODULE_5__["ThinEngine"].prototype._createDepthStencilTexture = function (size, options) {
var gl = this._gl;
var layers = size.layers || 0;
var target = layers !== 0 ? gl.TEXTURE_2D_ARRAY : gl.TEXTURE_2D;
var internalTexture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTextureSource"].Depth);
if (!this._caps.depthTextureExtension) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Error("Depth texture is not supported by your browser or hardware.");
return internalTexture;
}
var internalOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
this._bindTextureDirectly(target, internalTexture, true);
this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
var type = internalOptions.generateStencil ? gl.UNSIGNED_INT_24_8 : gl.UNSIGNED_INT;
var internalFormat = internalOptions.generateStencil ? gl.DEPTH_STENCIL : gl.DEPTH_COMPONENT;
var sizedFormat = internalFormat;
if (this.webGLVersion > 1) {
sizedFormat = internalOptions.generateStencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
}
if (internalTexture.is2DArray) {
gl.texImage3D(target, 0, sizedFormat, internalTexture.width, internalTexture.height, layers, 0, internalFormat, type, null);
}
else {
gl.texImage2D(target, 0, sizedFormat, internalTexture.width, internalTexture.height, 0, internalFormat, type, null);
}
this._bindTextureDirectly(target, null);
return internalTexture;
};
/***/ }),
/***/ "./Engines/Extensions/engine.renderTargetCube.ts":
/*!*******************************************************!*\
!*** ./Engines/Extensions/engine.renderTargetCube.ts ***!
\*******************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../constants */ "./Engines/constants.ts");
/* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../thinEngine */ "./Engines/thinEngine.ts");
_thinEngine__WEBPACK_IMPORTED_MODULE_4__["ThinEngine"].prototype.createRenderTargetCubeTexture = function (size, options) {
var fullOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT, samplingMode: _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE, format: _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA }, options);
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
// if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
else if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
var gl = this._gl;
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_1__["InternalTextureSource"].RenderTarget);
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTURETYPE_UNSIGNED_INT;
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
}
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
for (var face = 0; face < 6; face++) {
gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), size, size, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
}
// Create the framebuffer
var framebuffer = gl.createFramebuffer();
this._bindUnboundFramebuffer(framebuffer);
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
// MipMaps
if (fullOptions.generateMipMaps) {
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
}
// Unbind
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
this._bindUnboundFramebuffer(null);
texture._framebuffer = framebuffer;
texture.width = size;
texture.height = size;
texture.isReady = true;
texture.isCube = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture.format = fullOptions.format;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
this._internalTexturesCache.push(texture);
return texture;
};
/***/ }),
/***/ "./Engines/Extensions/engine.textureSelector.ts":
/*!******************************************************!*\
!*** ./Engines/Extensions/engine.textureSelector.ts ***!
\******************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../engine */ "./Engines/engine.ts");
function transformTextureUrl(url) {
var excludeFn = function (entry) {
var strRegExPattern = '\\b' + entry + '\\b';
return (url && (url === entry || url.match(new RegExp(strRegExPattern, 'g'))));
};
if (this._excludedCompressedTextures && this._excludedCompressedTextures.some(excludeFn)) {
return url;
}
var lastDot = url.lastIndexOf('.');
var lastQuestionMark = url.lastIndexOf('?');
var querystring = lastQuestionMark > -1 ? url.substring(lastQuestionMark, url.length) : '';
return (lastDot > -1 ? url.substring(0, lastDot) : url) + this._textureFormatInUse + querystring;
}
Object.defineProperty(_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype, "texturesSupported", {
get: function () {
// Intelligently add supported compressed formats in order to check for.
// Check for ASTC support first as it is most powerful and to be very cross platform.
// Next PVRTC & DXT, which are probably superior to ETC1/2.
// Likely no hardware which supports both PVR & DXT, so order matters little.
// ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
var texturesSupported = new Array();
if (this._caps.astc) {
texturesSupported.push('-astc.ktx');
}
if (this._caps.s3tc) {
texturesSupported.push('-dxt.ktx');
}
if (this._caps.pvrtc) {
texturesSupported.push('-pvrtc.ktx');
}
if (this._caps.etc2) {
texturesSupported.push('-etc2.ktx');
}
if (this._caps.etc1) {
texturesSupported.push('-etc1.ktx');
}
return texturesSupported;
},
enumerable: true,
configurable: true
});
Object.defineProperty(_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype, "textureFormatInUse", {
get: function () {
return this._textureFormatInUse || null;
},
enumerable: true,
configurable: true
});
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.setCompressedTextureExclusions = function (skippedFiles) {
this._excludedCompressedTextures = skippedFiles;
};
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.setTextureFormatToUse = function (formatsAvailable) {
var texturesSupported = this.texturesSupported;
for (var i = 0, len1 = texturesSupported.length; i < len1; i++) {
for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
if (texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
this._transformTextureUrl = transformTextureUrl.bind(this);
return this._textureFormatInUse = texturesSupported[i];
}
}
}
// actively set format to nothing, to allow this to be called more than once
// and possibly fail the 2nd time
this._textureFormatInUse = "";
this._transformTextureUrl = null;
return null;
};
/***/ }),
/***/ "./Engines/Extensions/engine.transformFeedback.ts":
/*!********************************************************!*\
!*** ./Engines/Extensions/engine.transformFeedback.ts ***!
\********************************************************/
/*! exports provided: _forceTransformFeedbackToBundle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _forceTransformFeedbackToBundle; });
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts");
/** @hidden */
var _forceTransformFeedbackToBundle = true;
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.createTransformFeedback = function () {
return this._gl.createTransformFeedback();
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.deleteTransformFeedback = function (value) {
this._gl.deleteTransformFeedback(value);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.bindTransformFeedback = function (value) {
this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.beginTransformFeedback = function (usePoints) {
if (usePoints === void 0) { usePoints = true; }
this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.endTransformFeedback = function () {
this._gl.endTransformFeedback();
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.setTranformFeedbackVaryings = function (program, value) {
this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.bindTransformFeedbackBuffer = function (value) {
this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value ? value.underlyingResource : null);
};
/***/ }),
/***/ "./Engines/Extensions/engine.uniformBuffer.ts":
/*!****************************************************!*\
!*** ./Engines/Extensions/engine.uniformBuffer.ts ***!
\****************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Meshes/WebGL/webGLDataBuffer */ "./Meshes/WebGL/webGLDataBuffer.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.createUniformBuffer = function (elements) {
var ubo = this._gl.createBuffer();
if (!ubo) {
throw new Error("Unable to create uniform buffer");
}
var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_1__["WebGLDataBuffer"](ubo);
this.bindUniformBuffer(result);
if (elements instanceof Float32Array) {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
}
else {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
}
this.bindUniformBuffer(null);
result.references = 1;
return result;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.createDynamicUniformBuffer = function (elements) {
var ubo = this._gl.createBuffer();
if (!ubo) {
throw new Error("Unable to create dynamic uniform buffer");
}
var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_1__["WebGLDataBuffer"](ubo);
this.bindUniformBuffer(result);
if (elements instanceof Float32Array) {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
}
else {
this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
}
this.bindUniformBuffer(null);
result.references = 1;
return result;
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
this.bindUniformBuffer(uniformBuffer);
if (offset === undefined) {
offset = 0;
}
if (count === undefined) {
if (elements instanceof Float32Array) {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
}
else {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
}
}
else {
if (elements instanceof Float32Array) {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
}
else {
this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
}
}
this.bindUniformBuffer(null);
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.bindUniformBuffer = function (buffer) {
this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer ? buffer.underlyingResource : null);
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.bindUniformBufferBase = function (buffer, location) {
this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer ? buffer.underlyingResource : null);
};
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.bindUniformBlock = function (pipelineContext, blockName, index) {
var program = pipelineContext.program;
var uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
this._gl.uniformBlockBinding(program, uniformLocation, index);
};
/***/ }),
/***/ "./Engines/Extensions/engine.videoTexture.ts":
/*!***************************************************!*\
!*** ./Engines/Extensions/engine.videoTexture.ts ***!
\***************************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Engines/thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _Misc_canvasGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/canvasGenerator */ "./Misc/canvasGenerator.ts");
_Engines_thinEngine__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"].prototype.updateVideoTexture = function (texture, video, invertY) {
if (!texture || texture._isDisabled) {
return;
}
var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
this._unpackFlipY(!invertY); // Video are upside down by default
try {
// Testing video texture support
if (this._videoTextureSupported === undefined) {
// clear old errors just in case.
this._gl.getError();
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
if (this._gl.getError() !== 0) {
this._videoTextureSupported = false;
}
else {
this._videoTextureSupported = true;
}
}
// Copy video through the current working canvas if video texture is not supported
if (!this._videoTextureSupported) {
if (!texture._workingCanvas) {
texture._workingCanvas = _Misc_canvasGenerator__WEBPACK_IMPORTED_MODULE_1__["CanvasGenerator"].CreateCanvas(texture.width, texture.height);
var context = texture._workingCanvas.getContext("2d");
if (!context) {
throw new Error("Unable to get 2d context");
}
texture._workingContext = context;
texture._workingCanvas.width = texture.width;
texture._workingCanvas.height = texture.height;
}
texture._workingContext.clearRect(0, 0, texture.width, texture.height);
texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
}
else {
this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
}
if (texture.generateMipMaps) {
this._gl.generateMipmap(this._gl.TEXTURE_2D);
}
if (!wasPreviouslyBound) {
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
}
// this.resetTextureCache();
texture.isReady = true;
}
catch (ex) {
// Something unexpected
// Let's disable the texture
texture._isDisabled = true;
}
};
/***/ }),
/***/ "./Engines/Extensions/engine.views.ts":
/*!********************************************!*\
!*** ./Engines/Extensions/engine.views.ts ***!
\********************************************/
/*! exports provided: EngineView */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineView", function() { return EngineView; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../engine */ "./Engines/engine.ts");
/**
* Class used to define an additional view for the engine
* @see https://doc.babylonjs.com/how_to/multi_canvases
*/
var EngineView = /** @class */ (function () {
function EngineView() {
}
return EngineView;
}());
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.getInputElement = function () {
return this.inputElement || this.getRenderingCanvas();
};
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.registerView = function (canvas, camera) {
var _this = this;
if (!this.views) {
this.views = [];
}
for (var _i = 0, _a = this.views; _i < _a.length; _i++) {
var view = _a[_i];
if (view.target === canvas) {
return view;
}
}
var masterCanvas = this.getRenderingCanvas();
if (masterCanvas) {
canvas.width = masterCanvas.width;
canvas.height = masterCanvas.height;
}
var newView = { target: canvas, camera: camera };
this.views.push(newView);
if (camera) {
camera.onDisposeObservable.add(function () {
_this.unRegisterView(canvas);
});
}
return newView;
};
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype.unRegisterView = function (canvas) {
if (!this.views) {
return this;
}
for (var _i = 0, _a = this.views; _i < _a.length; _i++) {
var view = _a[_i];
if (view.target === canvas) {
var index = this.views.indexOf(view);
if (index !== -1) {
this.views.splice(index, 1);
}
break;
}
}
return this;
};
_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].prototype._renderViews = function () {
if (!this.views) {
return false;
}
var parent = this.getRenderingCanvas();
if (!parent) {
return false;
}
for (var _i = 0, _a = this.views; _i < _a.length; _i++) {
var view = _a[_i];
var canvas = view.target;
var context = canvas.getContext("2d");
if (!context) {
continue;
}
var camera = view.camera;
var previewCamera = null;
var scene = null;
if (camera) {
scene = camera.getScene();
if (scene.activeCameras.length) {
continue;
}
this.activeView = view;
previewCamera = scene.activeCamera;
scene.activeCamera = camera;
}
// Set sizes
var dimsChanged = canvas.width !== canvas.clientWidth ||
canvas.height !== canvas.clientHeight;
if (canvas.clientWidth && canvas.clientHeight && dimsChanged) {
canvas.width = canvas.clientWidth;
canvas.height = canvas.clientHeight;
parent.width = canvas.clientWidth;
parent.height = canvas.clientHeight;
this.resize();
}
if (!parent.width || !parent.height) {
return false;
}
// Render the frame
this._renderFrame();
// Copy to target
context.drawImage(parent, 0, 0);
// Restore
if (previewCamera && scene) {
scene.activeCamera = previewCamera;
}
}
this.activeView = null;
return true;
};
/***/ }),
/***/ "./Engines/Extensions/engine.webVR.ts":
/*!********************************************!*\
!*** ./Engines/Extensions/engine.webVR.ts ***!
\********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Maths_math_size__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.size */ "./Maths/math.size.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/domManagement */ "./Misc/domManagement.ts");
Object.defineProperty(_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype, "isInVRExclusivePointerMode", {
get: function () {
return this._vrExclusivePointerMode;
},
enumerable: true,
configurable: true
});
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._prepareVRComponent = function () {
this._vrSupported = false;
this._vrExclusivePointerMode = false;
this.onVRDisplayChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
this.onVRRequestPresentComplete = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
this.onVRRequestPresentStart = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.isVRDevicePresent = function () {
return !!this._vrDisplay;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.getVRDevice = function () {
return this._vrDisplay;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.initWebVR = function () {
this.initWebVRAsync();
return this.onVRDisplayChangedObservable;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.initWebVRAsync = function () {
var _this = this;
var notifyObservers = function () {
var eventArgs = {
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
};
_this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
_this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
};
if (!this._onVrDisplayConnect) {
this._onVrDisplayConnect = function (event) {
_this._vrDisplay = event.display;
notifyObservers();
};
this._onVrDisplayDisconnect = function () {
_this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
_this._vrDisplay = undefined;
_this._frameHandler = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].QueueNewFrame(_this._boundRenderFunction);
notifyObservers();
};
this._onVrDisplayPresentChange = function () {
_this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
};
var hostWindow = this.getHostWindow();
if (hostWindow) {
hostWindow.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
hostWindow.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
hostWindow.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
}
}
this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
this._webVRInitPromise.then(notifyObservers);
return this._webVRInitPromise;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._getVRDisplaysAsync = function () {
var _this = this;
return new Promise(function (res) {
if (navigator.getVRDisplays) {
navigator.getVRDisplays().then(function (devices) {
_this._vrSupported = true;
// note that devices may actually be an empty array. This is fine;
// we expect this._vrDisplay to be undefined in this case.
_this._vrDisplay = devices[0];
res({
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
});
});
}
else {
_this._vrDisplay = undefined;
_this._vrSupported = false;
res({
vrDisplay: _this._vrDisplay,
vrSupported: _this._vrSupported
});
}
});
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.enableVR = function (options) {
var _this = this;
if (this._vrDisplay && !this._vrDisplay.isPresenting) {
var onResolved = function () {
_this.onVRRequestPresentComplete.notifyObservers(true);
_this._onVRFullScreenTriggered();
};
var onRejected = function () {
_this.onVRRequestPresentComplete.notifyObservers(false);
};
this.onVRRequestPresentStart.notifyObservers(this);
var presentationAttributes = {
highRefreshRate: this.vrPresentationAttributes ? this.vrPresentationAttributes.highRefreshRate : false,
foveationLevel: this.vrPresentationAttributes ? this.vrPresentationAttributes.foveationLevel : 1,
multiview: (this.getCaps().multiview || this.getCaps().oculusMultiview) && options.useMultiview
};
this._vrDisplay.requestPresent([Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ source: this.getRenderingCanvas(), attributes: presentationAttributes }, presentationAttributes)]).then(onResolved).catch(onRejected);
}
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._onVRFullScreenTriggered = function () {
if (this._vrDisplay && this._vrDisplay.isPresenting) {
//get the old size before we change
this._oldSize = new _Maths_math_size__WEBPACK_IMPORTED_MODULE_2__["Size"](this.getRenderWidth(), this.getRenderHeight());
this._oldHardwareScaleFactor = this.getHardwareScalingLevel();
//get the width and height, change the render size
var leftEye = this._vrDisplay.getEyeParameters('left');
this.setHardwareScalingLevel(1);
this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
}
else {
this.setHardwareScalingLevel(this._oldHardwareScaleFactor);
this.setSize(this._oldSize.width, this._oldSize.height);
}
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.disableVR = function () {
var _this = this;
if (this._vrDisplay && this._vrDisplay.isPresenting) {
this._vrDisplay.exitPresent()
.then(function () { return _this._onVRFullScreenTriggered(); })
.catch(function () { return _this._onVRFullScreenTriggered(); });
}
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_5__["DomManagement"].IsWindowObjectExist()) {
window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
if (this._onVrDisplayConnect) {
window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
if (this._onVrDisplayDisconnect) {
window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
}
if (this._onVrDisplayPresentChange) {
window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
}
this._onVrDisplayConnect = null;
this._onVrDisplayDisconnect = null;
}
}
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._connectVREvents = function (canvas, document) {
var _this = this;
this._onVRDisplayPointerRestricted = function () {
if (canvas) {
canvas.requestPointerLock();
}
};
this._onVRDisplayPointerUnrestricted = function () {
// Edge fix - for some reason document is not present and this is window
if (!document) {
var hostWindow = _this.getHostWindow();
if (hostWindow.document && hostWindow.document.exitPointerLock) {
hostWindow.document.exitPointerLock();
}
return;
}
if (!document.exitPointerLock) {
return;
}
document.exitPointerLock();
};
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_5__["DomManagement"].IsWindowObjectExist()) {
var hostWindow = this.getHostWindow();
hostWindow.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
hostWindow.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
}
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._submitVRFrame = function () {
// Submit frame to the vr device, if enabled
if (this._vrDisplay && this._vrDisplay.isPresenting) {
// TODO: We should only submit the frame if we read frameData successfully.
try {
this._vrDisplay.submitFrame();
}
catch (e) {
_Misc_tools__WEBPACK_IMPORTED_MODULE_4__["Tools"].Warn("webVR submitFrame has had an unexpected failure: " + e);
}
}
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype.isVRPresenting = function () {
return this._vrDisplay && this._vrDisplay.isPresenting;
};
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].prototype._requestVRFrame = function () {
this._frameHandler = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].QueueNewFrame(this._boundRenderFunction, this._vrDisplay);
};
/***/ }),
/***/ "./Engines/Extensions/index.ts":
/*!*************************************!*\
!*** ./Engines/Extensions/index.ts ***!
\*************************************/
/*! exports provided: _OcclusionDataStorage, _forceTransformFeedbackToBundle, EngineView */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _engine_alpha__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engine.alpha */ "./Engines/Extensions/engine.alpha.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_occlusionQuery__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engine.occlusionQuery */ "./Engines/Extensions/engine.occlusionQuery.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _engine_occlusionQuery__WEBPACK_IMPORTED_MODULE_1__["_OcclusionDataStorage"]; });
/* harmony import */ var _engine_transformFeedback__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./engine.transformFeedback */ "./Engines/Extensions/engine.transformFeedback.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _engine_transformFeedback__WEBPACK_IMPORTED_MODULE_2__["_forceTransformFeedbackToBundle"]; });
/* harmony import */ var _engine_multiview__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engine.multiview */ "./Engines/Extensions/engine.multiview.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_rawTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./engine.rawTexture */ "./Engines/Extensions/engine.rawTexture.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_dynamicTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./engine.dynamicTexture */ "./Engines/Extensions/engine.dynamicTexture.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_videoTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./engine.videoTexture */ "./Engines/Extensions/engine.videoTexture.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_multiRender__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./engine.multiRender */ "./Engines/Extensions/engine.multiRender.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./engine.cubeTexture */ "./Engines/Extensions/engine.cubeTexture.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_renderTarget__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./engine.renderTarget */ "./Engines/Extensions/engine.renderTarget.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_renderTargetCube__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./engine.renderTargetCube */ "./Engines/Extensions/engine.renderTargetCube.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_webVR__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./engine.webVR */ "./Engines/Extensions/engine.webVR.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_uniformBuffer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./engine.uniformBuffer */ "./Engines/Extensions/engine.uniformBuffer.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_dynamicBuffer__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./engine.dynamicBuffer */ "./Engines/Extensions/engine.dynamicBuffer.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_views__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./engine.views */ "./Engines/Extensions/engine.views.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineView", function() { return _engine_views__WEBPACK_IMPORTED_MODULE_14__["EngineView"]; });
/* harmony import */ var _engine_readTexture__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./engine.readTexture */ "./Engines/Extensions/engine.readTexture.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _engine_textureSelector__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./engine.textureSelector */ "./Engines/Extensions/engine.textureSelector.ts");
/* empty/unused harmony star reexport */
// must import first since nothing references the exports
/***/ }),
/***/ "./Engines/IPipelineContext.ts":
/*!*************************************!*\
!*** ./Engines/IPipelineContext.ts ***!
\*************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Engines/Processors/Expressions/Operators/shaderDefineAndOperator.ts":
/*!*****************************************************************************!*\
!*** ./Engines/Processors/Expressions/Operators/shaderDefineAndOperator.ts ***!
\*****************************************************************************/
/*! exports provided: ShaderDefineAndOperator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineAndOperator", function() { return ShaderDefineAndOperator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts");
/** @hidden */
var ShaderDefineAndOperator = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShaderDefineAndOperator, _super);
function ShaderDefineAndOperator() {
return _super !== null && _super.apply(this, arguments) || this;
}
ShaderDefineAndOperator.prototype.isTrue = function (preprocessors) {
return this.leftOperand.isTrue(preprocessors) && this.rightOperand.isTrue(preprocessors);
};
return ShaderDefineAndOperator;
}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"]));
/***/ }),
/***/ "./Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.ts":
/*!************************************************************************************!*\
!*** ./Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.ts ***!
\************************************************************************************/
/*! exports provided: ShaderDefineArithmeticOperator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineArithmeticOperator", function() { return ShaderDefineArithmeticOperator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts");
/** @hidden */
var ShaderDefineArithmeticOperator = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShaderDefineArithmeticOperator, _super);
function ShaderDefineArithmeticOperator(define, operand, testValue) {
var _this = _super.call(this) || this;
_this.define = define;
_this.operand = operand;
_this.testValue = testValue;
return _this;
}
ShaderDefineArithmeticOperator.prototype.isTrue = function (preprocessors) {
var value = preprocessors[this.define];
if (value === undefined) {
value = this.define;
}
var condition = false;
var left = parseInt(value);
var right = parseInt(this.testValue);
switch (this.operand) {
case ">":
condition = left > right;
break;
case "<":
condition = left < right;
break;
case "<=":
condition = left <= right;
break;
case ">=":
condition = left >= right;
break;
case "==":
condition = left === right;
break;
}
return condition;
};
return ShaderDefineArithmeticOperator;
}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"]));
/***/ }),
/***/ "./Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.ts":
/*!***********************************************************************************!*\
!*** ./Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.ts ***!
\***********************************************************************************/
/*! exports provided: ShaderDefineIsDefinedOperator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineIsDefinedOperator", function() { return ShaderDefineIsDefinedOperator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts");
/** @hidden */
var ShaderDefineIsDefinedOperator = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShaderDefineIsDefinedOperator, _super);
function ShaderDefineIsDefinedOperator(define, not) {
if (not === void 0) { not = false; }
var _this = _super.call(this) || this;
_this.define = define;
_this.not = not;
return _this;
}
ShaderDefineIsDefinedOperator.prototype.isTrue = function (preprocessors) {
var condition = preprocessors[this.define] !== undefined;
if (this.not) {
condition = !condition;
}
return condition;
};
return ShaderDefineIsDefinedOperator;
}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"]));
/***/ }),
/***/ "./Engines/Processors/Expressions/Operators/shaderDefineOrOperator.ts":
/*!****************************************************************************!*\
!*** ./Engines/Processors/Expressions/Operators/shaderDefineOrOperator.ts ***!
\****************************************************************************/
/*! exports provided: ShaderDefineOrOperator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineOrOperator", function() { return ShaderDefineOrOperator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts");
/** @hidden */
var ShaderDefineOrOperator = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShaderDefineOrOperator, _super);
function ShaderDefineOrOperator() {
return _super !== null && _super.apply(this, arguments) || this;
}
ShaderDefineOrOperator.prototype.isTrue = function (preprocessors) {
return this.leftOperand.isTrue(preprocessors) || this.rightOperand.isTrue(preprocessors);
};
return ShaderDefineOrOperator;
}(_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_1__["ShaderDefineExpression"]));
/***/ }),
/***/ "./Engines/Processors/Expressions/shaderDefineExpression.ts":
/*!******************************************************************!*\
!*** ./Engines/Processors/Expressions/shaderDefineExpression.ts ***!
\******************************************************************/
/*! exports provided: ShaderDefineExpression */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderDefineExpression", function() { return ShaderDefineExpression; });
/** @hidden */
var ShaderDefineExpression = /** @class */ (function () {
function ShaderDefineExpression() {
}
ShaderDefineExpression.prototype.isTrue = function (preprocessors) {
return true;
};
ShaderDefineExpression.postfixToInfix = function (postfix) {
var stack = [];
for (var _i = 0, postfix_1 = postfix; _i < postfix_1.length; _i++) {
var c = postfix_1[_i];
if (ShaderDefineExpression._OperatorPriority[c] === undefined) {
stack.push(c);
}
else {
var v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];
stack.length -= 2;
stack.push("(" + v2 + c + v1 + ")");
}
}
return stack[stack.length - 1];
};
ShaderDefineExpression.infixToPostfix = function (infix) {
var result = [];
var stackIdx = -1;
var pushOperand = function () {
operand = operand.trim();
if (operand !== '') {
result.push(operand);
operand = '';
}
};
var push = function (s) {
if (stackIdx < ShaderDefineExpression._Stack.length - 1) {
ShaderDefineExpression._Stack[++stackIdx] = s;
}
};
var peek = function () { return ShaderDefineExpression._Stack[stackIdx]; };
var pop = function () { return stackIdx === -1 ? '!!INVALID EXPRESSION!!' : ShaderDefineExpression._Stack[stackIdx--]; };
var idx = 0, operand = '';
while (idx < infix.length) {
var c = infix.charAt(idx), token = idx < infix.length - 1 ? infix.substr(idx, 2) : '';
if (c === '(') {
operand = '';
push(c);
}
else if (c === ')') {
pushOperand();
while (stackIdx !== -1 && peek() !== '(') {
result.push(pop());
}
pop();
}
else if (ShaderDefineExpression._OperatorPriority[token] > 1) {
pushOperand();
while (stackIdx !== -1 && ShaderDefineExpression._OperatorPriority[peek()] >= ShaderDefineExpression._OperatorPriority[token]) {
result.push(pop());
}
push(token);
idx++;
}
else {
operand += c;
}
idx++;
}
pushOperand();
while (stackIdx !== -1) {
if (peek() === '(') {
pop();
}
else {
result.push(pop());
}
}
return result;
};
ShaderDefineExpression._OperatorPriority = {
")": 0,
"(": 1,
"||": 2,
"&&": 3,
};
ShaderDefineExpression._Stack = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
return ShaderDefineExpression;
}());
/***/ }),
/***/ "./Engines/Processors/shaderCodeConditionNode.ts":
/*!*******************************************************!*\
!*** ./Engines/Processors/shaderCodeConditionNode.ts ***!
\*******************************************************/
/*! exports provided: ShaderCodeConditionNode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeConditionNode", function() { return ShaderCodeConditionNode; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaderCodeNode */ "./Engines/Processors/shaderCodeNode.ts");
/** @hidden */
var ShaderCodeConditionNode = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShaderCodeConditionNode, _super);
function ShaderCodeConditionNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
ShaderCodeConditionNode.prototype.process = function (preprocessors, options) {
for (var index = 0; index < this.children.length; index++) {
var node = this.children[index];
if (node.isValid(preprocessors)) {
return node.process(preprocessors, options);
}
}
return "";
};
return ShaderCodeConditionNode;
}(_shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"]));
/***/ }),
/***/ "./Engines/Processors/shaderCodeCursor.ts":
/*!************************************************!*\
!*** ./Engines/Processors/shaderCodeCursor.ts ***!
\************************************************/
/*! exports provided: ShaderCodeCursor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeCursor", function() { return ShaderCodeCursor; });
/** @hidden */
var ShaderCodeCursor = /** @class */ (function () {
function ShaderCodeCursor() {
}
Object.defineProperty(ShaderCodeCursor.prototype, "currentLine", {
get: function () {
return this._lines[this.lineIndex];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShaderCodeCursor.prototype, "canRead", {
get: function () {
return this.lineIndex < this._lines.length - 1;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShaderCodeCursor.prototype, "lines", {
set: function (value) {
this._lines = [];
for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
var line = value_1[_i];
// Prevent removing line break in macros.
if (line[0] === "#") {
this._lines.push(line);
continue;
}
var split = line.split(";");
for (var index = 0; index < split.length; index++) {
var subLine = split[index];
subLine = subLine.trim();
if (!subLine) {
continue;
}
this._lines.push(subLine + (index !== split.length - 1 ? ";" : ""));
}
}
},
enumerable: false,
configurable: true
});
return ShaderCodeCursor;
}());
/***/ }),
/***/ "./Engines/Processors/shaderCodeInliner.ts":
/*!*************************************************!*\
!*** ./Engines/Processors/shaderCodeInliner.ts ***!
\*************************************************/
/*! exports provided: ShaderCodeInliner */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeInliner", function() { return ShaderCodeInliner; });
/**
* Class used to inline functions in shader code
*/
var ShaderCodeInliner = /** @class */ (function () {
/**
* Initializes the inliner
* @param sourceCode shader code source to inline
* @param numMaxIterations maximum number of iterations (used to detect recursive calls)
*/
function ShaderCodeInliner(sourceCode, numMaxIterations) {
if (numMaxIterations === void 0) { numMaxIterations = 20; }
/** Gets or sets the debug mode */
this.debug = false;
this._sourceCode = sourceCode;
this._numMaxIterations = numMaxIterations;
this._functionDescr = [];
this.inlineToken = "#define inline";
}
Object.defineProperty(ShaderCodeInliner.prototype, "code", {
/** Gets the code after the inlining process */
get: function () {
return this._sourceCode;
},
enumerable: false,
configurable: true
});
/**
* Start the processing of the shader code
*/
ShaderCodeInliner.prototype.processCode = function () {
if (this.debug) {
console.log("Start inlining process (code size=" + this._sourceCode.length + ")...");
}
this._collectFunctions();
this._processInlining(this._numMaxIterations);
if (this.debug) {
console.log("End of inlining process.");
}
};
ShaderCodeInliner.prototype._collectFunctions = function () {
var startIndex = 0;
while (startIndex < this._sourceCode.length) {
// locate the function to inline and extract its name
var inlineTokenIndex = this._sourceCode.indexOf(this.inlineToken, startIndex);
if (inlineTokenIndex < 0) {
break;
}
var funcParamsStartIndex = this._sourceCode.indexOf("(", inlineTokenIndex + this.inlineToken.length);
if (funcParamsStartIndex < 0) {
if (this.debug) {
console.warn("Could not find the opening parenthesis after the token. startIndex=" + startIndex);
}
startIndex = inlineTokenIndex + this.inlineToken.length;
continue;
}
var funcNameMatch = ShaderCodeInliner._RegexpFindFunctionNameAndType.exec(this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex));
if (!funcNameMatch) {
if (this.debug) {
console.warn("Could not extract the name/type of the function from: " + this._sourceCode.substring(inlineTokenIndex + this.inlineToken.length, funcParamsStartIndex));
}
startIndex = inlineTokenIndex + this.inlineToken.length;
continue;
}
var _a = [funcNameMatch[3], funcNameMatch[4]], funcType = _a[0], funcName = _a[1];
// extract the parameters of the function as a whole string (without the leading / trailing parenthesis)
var funcParamsEndIndex = this._extractBetweenMarkers('(', ')', this._sourceCode, funcParamsStartIndex);
if (funcParamsEndIndex < 0) {
if (this.debug) {
console.warn("Could not extract the parameters the function '" + funcName + "' (type=" + funcType + "). funcParamsStartIndex=" + funcParamsStartIndex);
}
startIndex = inlineTokenIndex + this.inlineToken.length;
continue;
}
var funcParams = this._sourceCode.substring(funcParamsStartIndex + 1, funcParamsEndIndex);
// extract the body of the function (with the curly brackets)
var funcBodyStartIndex = this._skipWhitespaces(this._sourceCode, funcParamsEndIndex + 1);
if (funcBodyStartIndex === this._sourceCode.length) {
if (this.debug) {
console.warn("Could not extract the body of the function '" + funcName + "' (type=" + funcType + "). funcParamsEndIndex=" + funcParamsEndIndex);
}
startIndex = inlineTokenIndex + this.inlineToken.length;
continue;
}
var funcBodyEndIndex = this._extractBetweenMarkers('{', '}', this._sourceCode, funcBodyStartIndex);
if (funcBodyEndIndex < 0) {
if (this.debug) {
console.warn("Could not extract the body of the function '" + funcName + "' (type=" + funcType + "). funcBodyStartIndex=" + funcBodyStartIndex);
}
startIndex = inlineTokenIndex + this.inlineToken.length;
continue;
}
var funcBody = this._sourceCode.substring(funcBodyStartIndex, funcBodyEndIndex + 1);
// process the parameters: extract each names
var params = this._removeComments(funcParams).split(",");
var paramNames = [];
for (var p = 0; p < params.length; ++p) {
var param = params[p].trim();
var idx = param.lastIndexOf(" ");
if (idx >= 0) {
paramNames.push(param.substring(idx + 1));
}
}
if (funcType !== 'void') {
// for functions that return a value, we will replace "return" by "tempvarname = ", tempvarname being a unique generated name
paramNames.push('return');
}
// collect the function
this._functionDescr.push({
"name": funcName,
"type": funcType,
"parameters": paramNames,
"body": funcBody,
"callIndex": 0,
});
startIndex = funcBodyEndIndex + 1;
// remove the function from the source code
var partBefore = inlineTokenIndex > 0 ? this._sourceCode.substring(0, inlineTokenIndex) : "";
var partAfter = funcBodyEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(funcBodyEndIndex + 1) : "";
this._sourceCode = partBefore + partAfter;
startIndex -= funcBodyEndIndex + 1 - inlineTokenIndex;
}
if (this.debug) {
console.log("Collect functions: " + this._functionDescr.length + " functions found. functionDescr=", this._functionDescr);
}
};
ShaderCodeInliner.prototype._processInlining = function (numMaxIterations) {
if (numMaxIterations === void 0) { numMaxIterations = 20; }
while (numMaxIterations-- >= 0) {
if (!this._replaceFunctionCallsByCode()) {
break;
}
}
if (this.debug) {
console.log("numMaxIterations is " + numMaxIterations + " after inlining process");
}
return numMaxIterations >= 0;
};
ShaderCodeInliner.prototype._extractBetweenMarkers = function (markerOpen, markerClose, block, startIndex) {
var currPos = startIndex, openMarkers = 0, waitForChar = '';
while (currPos < block.length) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case markerOpen:
openMarkers++;
break;
case markerClose:
openMarkers--;
break;
case '"':
case "'":
case "`":
waitForChar = currChar;
break;
case '/':
if (currPos + 1 < block.length) {
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
}
else if (nextChar === '*') {
waitForChar = '*/';
}
}
break;
}
}
else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = '');
}
else {
waitForChar = '';
}
}
else if (waitForChar === '*/' && currChar === '*' && currPos + 1 < block.length) {
block.charAt(currPos + 1) === '/' && (waitForChar = '');
if (waitForChar === '') {
currPos++;
}
}
}
currPos++;
if (openMarkers === 0) {
break;
}
}
return openMarkers === 0 ? currPos - 1 : -1;
};
ShaderCodeInliner.prototype._skipWhitespaces = function (s, index) {
while (index < s.length) {
var c = s[index];
if (c !== ' ' && c !== '\n' && c !== '\r' && c !== '\t' && c !== '\u000a' && c !== '\u00a0') {
break;
}
index++;
}
return index;
};
ShaderCodeInliner.prototype._removeComments = function (block) {
var currPos = 0, waitForChar = '', inComments = false, s = [];
while (currPos < block.length) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case '"':
case "'":
case "`":
waitForChar = currChar;
break;
case '/':
if (currPos + 1 < block.length) {
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
inComments = true;
}
else if (nextChar === '*') {
waitForChar = '*/';
inComments = true;
}
}
break;
}
if (!inComments) {
s.push(currChar);
}
}
else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = '');
s.push(currChar);
}
else {
waitForChar = '';
inComments = false;
}
}
else if (waitForChar === '*/' && currChar === '*' && currPos + 1 < block.length) {
block.charAt(currPos + 1) === '/' && (waitForChar = '');
if (waitForChar === '') {
inComments = false;
currPos++;
}
}
else {
if (!inComments) {
s.push(currChar);
}
}
}
currPos++;
}
return s.join('');
};
ShaderCodeInliner.prototype._replaceFunctionCallsByCode = function () {
var doAgain = false;
for (var _i = 0, _a = this._functionDescr; _i < _a.length; _i++) {
var func = _a[_i];
var name_1 = func.name, type = func.type, parameters = func.parameters, body = func.body;
var startIndex = 0;
while (startIndex < this._sourceCode.length) {
// Look for the function name in the source code
var functionCallIndex = this._sourceCode.indexOf(name_1, startIndex);
if (functionCallIndex < 0) {
break;
}
// Find the opening parenthesis
var callParamsStartIndex = this._skipWhitespaces(this._sourceCode, functionCallIndex + name_1.length);
if (callParamsStartIndex === this._sourceCode.length || this._sourceCode.charAt(callParamsStartIndex) !== '(') {
startIndex = functionCallIndex + name_1.length;
continue;
}
// extract the parameters of the function call as a whole string (without the leading / trailing parenthesis)
var callParamsEndIndex = this._extractBetweenMarkers('(', ')', this._sourceCode, callParamsStartIndex);
if (callParamsEndIndex < 0) {
if (this.debug) {
console.warn("Could not extract the parameters of the function call. Function '" + name_1 + "' (type=" + type + "). callParamsStartIndex=" + callParamsStartIndex);
}
startIndex = functionCallIndex + name_1.length;
continue;
}
var callParams = this._sourceCode.substring(callParamsStartIndex + 1, callParamsEndIndex);
// process the parameter call: extract each names
var params = this._removeComments(callParams).split(",");
var paramNames = [];
for (var p = 0; p < params.length; ++p) {
var param = params[p].trim();
paramNames.push(param);
}
var retParamName = type !== 'void' ? name_1 + '_' + (func.callIndex++) : null;
if (retParamName) {
paramNames.push(retParamName + ' =');
}
if (paramNames.length !== parameters.length) {
if (this.debug) {
console.warn("Invalid function call: not the same number of parameters for the call than the number expected by the function. Function '" + name_1 + "' (type=" + type + "). function parameters=" + parameters + ", call parameters=" + paramNames);
}
startIndex = functionCallIndex + name_1.length;
continue;
}
startIndex = callParamsEndIndex + 1;
// replace the function call by the body function
var funcBody = this._replaceNames(body, parameters, paramNames);
var partBefore = functionCallIndex > 0 ? this._sourceCode.substring(0, functionCallIndex) : "";
var partAfter = callParamsEndIndex + 1 < this._sourceCode.length - 1 ? this._sourceCode.substring(callParamsEndIndex + 1) : "";
if (retParamName) {
// case where the function returns a value. We generate:
// FUNCTYPE retParamName;
// {function body}
// and replace the function call by retParamName
var injectDeclarationIndex = this._findBackward(this._sourceCode, functionCallIndex - 1, '\n');
partBefore = this._sourceCode.substring(0, injectDeclarationIndex + 1);
var partBetween = this._sourceCode.substring(injectDeclarationIndex + 1, functionCallIndex);
this._sourceCode = partBefore + type + " " + retParamName + ";\n" + funcBody + "\n" + partBetween + retParamName + partAfter;
if (this.debug) {
console.log("Replace function call by code. Function '" + name_1 + "' (type=" + type + "). injectDeclarationIndex=" + injectDeclarationIndex);
}
}
else {
// simple case where the return value of the function is "void"
this._sourceCode = partBefore + funcBody + partAfter;
startIndex += funcBody.length - (callParamsEndIndex + 1 - functionCallIndex);
if (this.debug) {
console.log("Replace function call by code. Function '" + name_1 + "' (type=" + type + "). functionCallIndex=" + functionCallIndex);
}
}
doAgain = true;
}
}
return doAgain;
};
ShaderCodeInliner.prototype._findBackward = function (s, index, c) {
while (index >= 0 && s.charAt(index) !== c) {
index--;
}
return index;
};
ShaderCodeInliner.prototype._escapeRegExp = function (s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
ShaderCodeInliner.prototype._replaceNames = function (code, sources, destinations) {
for (var i = 0; i < sources.length; ++i) {
var source = new RegExp(this._escapeRegExp(sources[i]), 'g'), destination = destinations[i];
code = code.replace(source, destination);
}
return code;
};
ShaderCodeInliner._RegexpFindFunctionNameAndType = /((\s+?)(\w+)\s+(\w+)\s*?)$/;
return ShaderCodeInliner;
}());
/***/ }),
/***/ "./Engines/Processors/shaderCodeNode.ts":
/*!**********************************************!*\
!*** ./Engines/Processors/shaderCodeNode.ts ***!
\**********************************************/
/*! exports provided: ShaderCodeNode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeNode", function() { return ShaderCodeNode; });
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/stringTools */ "./Misc/stringTools.ts");
/** @hidden */
var ShaderCodeNode = /** @class */ (function () {
function ShaderCodeNode() {
this.children = [];
}
ShaderCodeNode.prototype.isValid = function (preprocessors) {
return true;
};
ShaderCodeNode.prototype.process = function (preprocessors, options) {
var result = "";
if (this.line) {
var value = this.line;
var processor = options.processor;
if (processor) {
// This must be done before other replacements to avoid mistakenly changing something that was already changed.
if (processor.lineProcessor) {
value = processor.lineProcessor(value, options.isFragment);
}
if (processor.attributeProcessor && _Misc_stringTools__WEBPACK_IMPORTED_MODULE_0__["StringTools"].StartsWith(this.line, "attribute")) {
value = processor.attributeProcessor(this.line);
}
else if (processor.varyingProcessor && _Misc_stringTools__WEBPACK_IMPORTED_MODULE_0__["StringTools"].StartsWith(this.line, "varying")) {
value = processor.varyingProcessor(this.line, options.isFragment);
}
else if ((processor.uniformProcessor || processor.uniformBufferProcessor) && _Misc_stringTools__WEBPACK_IMPORTED_MODULE_0__["StringTools"].StartsWith(this.line, "uniform")) {
var regex = /uniform (.+) (.+)/;
if (regex.test(this.line)) { // uniform
if (processor.uniformProcessor) {
value = processor.uniformProcessor(this.line, options.isFragment);
}
}
else { // Uniform buffer
if (processor.uniformBufferProcessor) {
value = processor.uniformBufferProcessor(this.line, options.isFragment);
options.lookForClosingBracketForUniformBuffer = true;
}
}
}
if (processor.endOfUniformBufferProcessor) {
if (options.lookForClosingBracketForUniformBuffer && this.line.indexOf("}") !== -1) {
options.lookForClosingBracketForUniformBuffer = false;
value = processor.endOfUniformBufferProcessor(this.line, options.isFragment);
}
}
}
result += value + "\r\n";
}
this.children.forEach(function (child) {
result += child.process(preprocessors, options);
});
if (this.additionalDefineKey) {
preprocessors[this.additionalDefineKey] = this.additionalDefineValue || "true";
}
return result;
};
return ShaderCodeNode;
}());
/***/ }),
/***/ "./Engines/Processors/shaderCodeTestNode.ts":
/*!**************************************************!*\
!*** ./Engines/Processors/shaderCodeTestNode.ts ***!
\**************************************************/
/*! exports provided: ShaderCodeTestNode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeTestNode", function() { return ShaderCodeTestNode; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaderCodeNode */ "./Engines/Processors/shaderCodeNode.ts");
/** @hidden */
var ShaderCodeTestNode = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShaderCodeTestNode, _super);
function ShaderCodeTestNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
ShaderCodeTestNode.prototype.isValid = function (preprocessors) {
return this.testExpression.isTrue(preprocessors);
};
return ShaderCodeTestNode;
}(_shaderCodeNode__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeNode"]));
/***/ }),
/***/ "./Engines/Processors/shaderProcessor.ts":
/*!***********************************************!*\
!*** ./Engines/Processors/shaderProcessor.ts ***!
\***********************************************/
/*! exports provided: ShaderProcessor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShaderProcessor", function() { return ShaderProcessor; });
/* harmony import */ var _shaderCodeNode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shaderCodeNode */ "./Engines/Processors/shaderCodeNode.ts");
/* harmony import */ var _shaderCodeCursor__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shaderCodeCursor */ "./Engines/Processors/shaderCodeCursor.ts");
/* harmony import */ var _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./shaderCodeConditionNode */ "./Engines/Processors/shaderCodeConditionNode.ts");
/* harmony import */ var _shaderCodeTestNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./shaderCodeTestNode */ "./Engines/Processors/shaderCodeTestNode.ts");
/* harmony import */ var _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineIsDefinedOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineIsDefinedOperator.ts");
/* harmony import */ var _Expressions_Operators_shaderDefineOrOperator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineOrOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineOrOperator.ts");
/* harmony import */ var _Expressions_Operators_shaderDefineAndOperator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineAndOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineAndOperator.ts");
/* harmony import */ var _Expressions_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Expressions/shaderDefineExpression */ "./Engines/Processors/Expressions/shaderDefineExpression.ts");
/* harmony import */ var _Expressions_Operators_shaderDefineArithmeticOperator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Expressions/Operators/shaderDefineArithmeticOperator */ "./Engines/Processors/Expressions/Operators/shaderDefineArithmeticOperator.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts");
var regexSE = /defined\s*?\((.+?)\)/g;
var regexSERevert = /defined\s*?\[(.+?)\]/g;
/** @hidden */
var ShaderProcessor = /** @class */ (function () {
function ShaderProcessor() {
}
ShaderProcessor.Process = function (sourceCode, options, callback) {
var _this = this;
this._ProcessIncludes(sourceCode, options, function (codeWithIncludes) {
var migratedCode = _this._ProcessShaderConversion(codeWithIncludes, options);
callback(migratedCode);
});
};
ShaderProcessor._ProcessPrecision = function (source, options) {
var shouldUseHighPrecisionShader = options.shouldUseHighPrecisionShader;
if (source.indexOf("precision highp float") === -1) {
if (!shouldUseHighPrecisionShader) {
source = "precision mediump float;\n" + source;
}
else {
source = "precision highp float;\n" + source;
}
}
else {
if (!shouldUseHighPrecisionShader) { // Moving highp to mediump
source = source.replace("precision highp float", "precision mediump float");
}
}
return source;
};
ShaderProcessor._ExtractOperation = function (expression) {
var regex = /defined\((.+)\)/;
var match = regex.exec(expression);
if (match && match.length) {
return new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_4__["ShaderDefineIsDefinedOperator"](match[1].trim(), expression[0] === "!");
}
var operators = ["==", ">=", "<=", "<", ">"];
var operator = "";
var indexOperator = 0;
for (var _i = 0, operators_1 = operators; _i < operators_1.length; _i++) {
operator = operators_1[_i];
indexOperator = expression.indexOf(operator);
if (indexOperator > -1) {
break;
}
}
if (indexOperator === -1) {
return new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_4__["ShaderDefineIsDefinedOperator"](expression);
}
var define = expression.substring(0, indexOperator).trim();
var value = expression.substring(indexOperator + operator.length).trim();
return new _Expressions_Operators_shaderDefineArithmeticOperator__WEBPACK_IMPORTED_MODULE_8__["ShaderDefineArithmeticOperator"](define, operator, value);
};
ShaderProcessor._BuildSubExpression = function (expression) {
expression = expression.replace(regexSE, "defined[$1]");
var postfix = _Expressions_shaderDefineExpression__WEBPACK_IMPORTED_MODULE_7__["ShaderDefineExpression"].infixToPostfix(expression);
var stack = [];
for (var _i = 0, postfix_1 = postfix; _i < postfix_1.length; _i++) {
var c = postfix_1[_i];
if (c !== '||' && c !== '&&') {
stack.push(c);
}
else if (stack.length >= 2) {
var v1 = stack[stack.length - 1], v2 = stack[stack.length - 2];
stack.length -= 2;
var operator = c == '&&' ? new _Expressions_Operators_shaderDefineAndOperator__WEBPACK_IMPORTED_MODULE_6__["ShaderDefineAndOperator"]() : new _Expressions_Operators_shaderDefineOrOperator__WEBPACK_IMPORTED_MODULE_5__["ShaderDefineOrOperator"]();
if (typeof (v1) === 'string') {
v1 = v1.replace(regexSERevert, "defined($1)");
}
if (typeof (v2) === 'string') {
v2 = v2.replace(regexSERevert, "defined($1)");
}
operator.leftOperand = typeof (v2) === 'string' ? this._ExtractOperation(v2) : v2;
operator.rightOperand = typeof (v1) === 'string' ? this._ExtractOperation(v1) : v1;
stack.push(operator);
}
}
var result = stack[stack.length - 1];
if (typeof (result) === 'string') {
result = result.replace(regexSERevert, "defined($1)");
}
// note: stack.length !== 1 if there was an error in the parsing
return typeof (result) === 'string' ? this._ExtractOperation(result) : result;
};
ShaderProcessor._BuildExpression = function (line, start) {
var node = new _shaderCodeTestNode__WEBPACK_IMPORTED_MODULE_3__["ShaderCodeTestNode"]();
var command = line.substring(0, start);
var expression = line.substring(start);
expression = expression.substring(0, ((expression.indexOf("//") + 1) || (expression.length + 1)) - 1).trim();
if (command === "#ifdef") {
node.testExpression = new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_4__["ShaderDefineIsDefinedOperator"](expression);
}
else if (command === "#ifndef") {
node.testExpression = new _Expressions_Operators_shaderDefineIsDefinedOperator__WEBPACK_IMPORTED_MODULE_4__["ShaderDefineIsDefinedOperator"](expression, true);
}
else {
node.testExpression = this._BuildSubExpression(expression);
}
return node;
};
ShaderProcessor._MoveCursorWithinIf = function (cursor, rootNode, ifNode) {
var line = cursor.currentLine;
while (this._MoveCursor(cursor, ifNode)) {
line = cursor.currentLine;
var first5 = line.substring(0, 5).toLowerCase();
if (first5 === "#else") {
var elseNode = new _shaderCodeNode__WEBPACK_IMPORTED_MODULE_0__["ShaderCodeNode"]();
rootNode.children.push(elseNode);
this._MoveCursor(cursor, elseNode);
return;
}
else if (first5 === "#elif") {
var elifNode = this._BuildExpression(line, 5);
rootNode.children.push(elifNode);
ifNode = elifNode;
}
}
};
ShaderProcessor._MoveCursor = function (cursor, rootNode) {
while (cursor.canRead) {
cursor.lineIndex++;
var line = cursor.currentLine;
var keywords = /(#ifdef)|(#else)|(#elif)|(#endif)|(#ifndef)|(#if)/;
var matches = keywords.exec(line);
if (matches && matches.length) {
var keyword = matches[0];
switch (keyword) {
case "#ifdef": {
var newRootNode = new _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_2__["ShaderCodeConditionNode"]();
rootNode.children.push(newRootNode);
var ifNode = this._BuildExpression(line, 6);
newRootNode.children.push(ifNode);
this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
break;
}
case "#else":
case "#elif":
return true;
case "#endif":
return false;
case "#ifndef": {
var newRootNode = new _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_2__["ShaderCodeConditionNode"]();
rootNode.children.push(newRootNode);
var ifNode = this._BuildExpression(line, 7);
newRootNode.children.push(ifNode);
this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
break;
}
case "#if": {
var newRootNode = new _shaderCodeConditionNode__WEBPACK_IMPORTED_MODULE_2__["ShaderCodeConditionNode"]();
var ifNode = this._BuildExpression(line, 3);
rootNode.children.push(newRootNode);
newRootNode.children.push(ifNode);
this._MoveCursorWithinIf(cursor, newRootNode, ifNode);
break;
}
}
}
else {
var newNode = new _shaderCodeNode__WEBPACK_IMPORTED_MODULE_0__["ShaderCodeNode"]();
newNode.line = line;
rootNode.children.push(newNode);
// Detect additional defines
if (line[0] === "#" && line[1] === "d") {
var split = line.replace(";", "").split(" ");
newNode.additionalDefineKey = split[1];
if (split.length === 3) {
newNode.additionalDefineValue = split[2];
}
}
}
}
return false;
};
ShaderProcessor._EvaluatePreProcessors = function (sourceCode, preprocessors, options) {
var rootNode = new _shaderCodeNode__WEBPACK_IMPORTED_MODULE_0__["ShaderCodeNode"]();
var cursor = new _shaderCodeCursor__WEBPACK_IMPORTED_MODULE_1__["ShaderCodeCursor"]();
cursor.lineIndex = -1;
cursor.lines = sourceCode.split("\n");
// Decompose (We keep it in 2 steps so it is easier to maintain and perf hit is insignificant)
this._MoveCursor(cursor, rootNode);
// Recompose
return rootNode.process(preprocessors, options);
};
ShaderProcessor._PreparePreProcessors = function (options) {
var defines = options.defines;
var preprocessors = {};
for (var _i = 0, defines_1 = defines; _i < defines_1.length; _i++) {
var define = defines_1[_i];
var keyValue = define.replace("#define", "").replace(";", "").trim();
var split = keyValue.split(" ");
preprocessors[split[0]] = split.length > 1 ? split[1] : "";
}
preprocessors["GL_ES"] = "true";
preprocessors["__VERSION__"] = options.version;
preprocessors[options.platformName] = "true";
return preprocessors;
};
ShaderProcessor._ProcessShaderConversion = function (sourceCode, options) {
var preparedSourceCode = this._ProcessPrecision(sourceCode, options);
if (!options.processor) {
return preparedSourceCode;
}
// Already converted
if (preparedSourceCode.indexOf("#version 3") !== -1) {
return preparedSourceCode.replace("#version 300 es", "");
}
var defines = options.defines;
var preprocessors = this._PreparePreProcessors(options);
// General pre processing
if (options.processor.preProcessor) {
preparedSourceCode = options.processor.preProcessor(preparedSourceCode, defines, options.isFragment);
}
preparedSourceCode = this._EvaluatePreProcessors(preparedSourceCode, preprocessors, options);
// Post processing
if (options.processor.postProcessor) {
preparedSourceCode = options.processor.postProcessor(preparedSourceCode, defines, options.isFragment);
}
return preparedSourceCode;
};
ShaderProcessor._ProcessIncludes = function (sourceCode, options, callback) {
var _this = this;
var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
var match = regex.exec(sourceCode);
var returnValue = new String(sourceCode);
var keepProcessing = false;
while (match != null) {
var includeFile = match[1];
// Uniform declaration
if (includeFile.indexOf("__decl__") !== -1) {
includeFile = includeFile.replace(/__decl__/, "");
if (options.supportsUniformBuffers) {
includeFile = includeFile.replace(/Vertex/, "Ubo");
includeFile = includeFile.replace(/Fragment/, "Ubo");
}
includeFile = includeFile + "Declaration";
}
if (options.includesShadersStore[includeFile]) {
// Substitution
var includeContent = options.includesShadersStore[includeFile];
if (match[2]) {
var splits = match[3].split(",");
for (var index = 0; index < splits.length; index += 2) {
var source = new RegExp(splits[index], "g");
var dest = splits[index + 1];
includeContent = includeContent.replace(source, dest);
}
}
if (match[4]) {
var indexString = match[5];
if (indexString.indexOf("..") !== -1) {
var indexSplits = indexString.split("..");
var minIndex = parseInt(indexSplits[0]);
var maxIndex = parseInt(indexSplits[1]);
var sourceIncludeContent = includeContent.slice(0);
includeContent = "";
if (isNaN(maxIndex)) {
maxIndex = options.indexParameters[indexSplits[1]];
}
for (var i = minIndex; i < maxIndex; i++) {
if (!options.supportsUniformBuffers) {
// Ubo replacement
sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
return p1 + "{X}";
});
}
includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
}
}
else {
if (!options.supportsUniformBuffers) {
// Ubo replacement
includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
return p1 + "{X}";
});
}
includeContent = includeContent.replace(/\{X\}/g, indexString);
}
}
// Replace
returnValue = returnValue.replace(match[0], includeContent);
keepProcessing = keepProcessing || includeContent.indexOf("#include<") >= 0;
}
else {
var includeShaderUrl = options.shadersRepository + "ShadersInclude/" + includeFile + ".fx";
ShaderProcessor._FileToolsLoadFile(includeShaderUrl, function (fileContent) {
options.includesShadersStore[includeFile] = fileContent;
_this._ProcessIncludes(returnValue, options, callback);
});
return;
}
match = regex.exec(sourceCode);
}
if (keepProcessing) {
this._ProcessIncludes(returnValue.toString(), options, callback);
}
else {
callback(returnValue);
}
};
/**
* Loads a file from a url
* @param url url to load
* @param onSuccess callback called when the file successfully loads
* @param onProgress callback called while file is loading (if the server supports this mode)
* @param offlineProvider defines the offline provider for caching
* @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
* @param onError callback called when the file fails to load
* @returns a file request object
* @hidden
*/
ShaderProcessor._FileToolsLoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_9__["_DevTools"].WarnImport("FileTools");
};
return ShaderProcessor;
}());
/***/ }),
/***/ "./Engines/WebGL/webGL2ShaderProcessors.ts":
/*!*************************************************!*\
!*** ./Engines/WebGL/webGL2ShaderProcessors.ts ***!
\*************************************************/
/*! exports provided: WebGL2ShaderProcessor */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGL2ShaderProcessor", function() { return WebGL2ShaderProcessor; });
/** @hidden */
var WebGL2ShaderProcessor = /** @class */ (function () {
function WebGL2ShaderProcessor() {
}
WebGL2ShaderProcessor.prototype.attributeProcessor = function (attribute) {
return attribute.replace("attribute", "in");
};
WebGL2ShaderProcessor.prototype.varyingProcessor = function (varying, isFragment) {
return varying.replace("varying", isFragment ? "in" : "out");
};
WebGL2ShaderProcessor.prototype.postProcessor = function (code, defines, isFragment) {
var hasDrawBuffersExtension = code.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
// Remove extensions
var regex = /#extension.+(GL_OVR_multiview2|GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
code = code.replace(regex, "");
// Replace instructions
code = code.replace(/texture2D\s*\(/g, "texture(");
if (isFragment) {
code = code.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
code = code.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
code = code.replace(/textureCube\s*\(/g, "texture(");
code = code.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
code = code.replace(/gl_FragColor/g, "glFragColor");
code = code.replace(/gl_FragData/g, "glFragData");
code = code.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
}
else {
var hasMultiviewExtension = defines.indexOf("#define MULTIVIEW") !== -1;
if (hasMultiviewExtension) {
return "#extension GL_OVR_multiview2 : require\nlayout (num_views = 2) in;\n" + code;
}
}
return code;
};
return WebGL2ShaderProcessor;
}());
/***/ }),
/***/ "./Engines/WebGL/webGLPipelineContext.ts":
/*!***********************************************!*\
!*** ./Engines/WebGL/webGLPipelineContext.ts ***!
\***********************************************/
/*! exports provided: WebGLPipelineContext */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebGLPipelineContext", function() { return WebGLPipelineContext; });
/** @hidden */
var WebGLPipelineContext = /** @class */ (function () {
function WebGLPipelineContext() {
this.vertexCompilationError = null;
this.fragmentCompilationError = null;
this.programLinkError = null;
this.programValidationError = null;
}
Object.defineProperty(WebGLPipelineContext.prototype, "isAsync", {
get: function () {
return this.isParallelCompiled;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WebGLPipelineContext.prototype, "isReady", {
get: function () {
if (this.program) {
if (this.isParallelCompiled) {
return this.engine._isRenderingStateCompiled(this);
}
return true;
}
return false;
},
enumerable: false,
configurable: true
});
WebGLPipelineContext.prototype._handlesSpectorRebuildCallback = function (onCompiled) {
if (onCompiled && this.program) {
onCompiled(this.program);
}
};
WebGLPipelineContext.prototype._getVertexShaderCode = function () {
return this.vertexShader ? this.engine._getShaderSource(this.vertexShader) : null;
};
WebGLPipelineContext.prototype._getFragmentShaderCode = function () {
return this.fragmentShader ? this.engine._getShaderSource(this.fragmentShader) : null;
};
return WebGLPipelineContext;
}());
/***/ }),
/***/ "./Engines/constants.ts":
/*!******************************!*\
!*** ./Engines/constants.ts ***!
\******************************/
/*! exports provided: Constants */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return Constants; });
/** Defines the cross module used constants to avoid circular dependncies */
var Constants = /** @class */ (function () {
function Constants() {
}
/** Defines that alpha blending is disabled */
Constants.ALPHA_DISABLE = 0;
/** Defines that alpha blending is SRC ALPHA * SRC + DEST */
Constants.ALPHA_ADD = 1;
/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
Constants.ALPHA_COMBINE = 2;
/** Defines that alpha blending is DEST - SRC * DEST */
Constants.ALPHA_SUBTRACT = 3;
/** Defines that alpha blending is SRC * DEST */
Constants.ALPHA_MULTIPLY = 4;
/** Defines that alpha blending is SRC ALPHA * SRC + (1 - SRC) * DEST */
Constants.ALPHA_MAXIMIZED = 5;
/** Defines that alpha blending is SRC + DEST */
Constants.ALPHA_ONEONE = 6;
/** Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST */
Constants.ALPHA_PREMULTIPLIED = 7;
/**
* Defines that alpha blending is SRC + (1 - SRC ALPHA) * DEST
* Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
*/
Constants.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
/** Defines that alpha blending is CST * SRC + (1 - CST) * DEST */
Constants.ALPHA_INTERPOLATE = 9;
/**
* Defines that alpha blending is SRC + (1 - SRC) * DEST
* Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
*/
Constants.ALPHA_SCREENMODE = 10;
/**
* Defines that alpha blending is SRC + DST
* Alpha will be set to SRC ALPHA + DST ALPHA
*/
Constants.ALPHA_ONEONE_ONEONE = 11;
/**
* Defines that alpha blending is SRC * DST ALPHA + DST
* Alpha will be set to 0
*/
Constants.ALPHA_ALPHATOCOLOR = 12;
/**
* Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)
*/
Constants.ALPHA_REVERSEONEMINUS = 13;
/**
* Defines that alpha blending is SRC + DST * (1 - SRC ALPHA)
* Alpha will be set to SRC ALPHA + DST ALPHA * (1 - SRC ALPHA)
*/
Constants.ALPHA_SRC_DSTONEMINUSSRCALPHA = 14;
/**
* Defines that alpha blending is SRC + DST
* Alpha will be set to SRC ALPHA
*/
Constants.ALPHA_ONEONE_ONEZERO = 15;
/**
* Defines that alpha blending is SRC * (1 - DST) + DST * (1 - SRC)
* Alpha will be set to DST ALPHA
*/
Constants.ALPHA_EXCLUSION = 16;
/** Defines that alpha blending equation a SUM */
Constants.ALPHA_EQUATION_ADD = 0;
/** Defines that alpha blending equation a SUBSTRACTION */
Constants.ALPHA_EQUATION_SUBSTRACT = 1;
/** Defines that alpha blending equation a REVERSE SUBSTRACTION */
Constants.ALPHA_EQUATION_REVERSE_SUBTRACT = 2;
/** Defines that alpha blending equation a MAX operation */
Constants.ALPHA_EQUATION_MAX = 3;
/** Defines that alpha blending equation a MIN operation */
Constants.ALPHA_EQUATION_MIN = 4;
/**
* Defines that alpha blending equation a DARKEN operation:
* It takes the min of the src and sums the alpha channels.
*/
Constants.ALPHA_EQUATION_DARKEN = 5;
/** Defines that the ressource is not delayed*/
Constants.DELAYLOADSTATE_NONE = 0;
/** Defines that the ressource was successfully delay loaded */
Constants.DELAYLOADSTATE_LOADED = 1;
/** Defines that the ressource is currently delay loading */
Constants.DELAYLOADSTATE_LOADING = 2;
/** Defines that the ressource is delayed and has not started loading */
Constants.DELAYLOADSTATE_NOTLOADED = 4;
// Depht or Stencil test Constants.
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
Constants.NEVER = 0x0200;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
Constants.ALWAYS = 0x0207;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
Constants.LESS = 0x0201;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
Constants.EQUAL = 0x0202;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
Constants.LEQUAL = 0x0203;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
Constants.GREATER = 0x0204;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
Constants.GEQUAL = 0x0206;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
Constants.NOTEQUAL = 0x0205;
// Stencil Actions Constants.
/** Passed to stencilOperation to specify that stencil value must be kept */
Constants.KEEP = 0x1E00;
/** Passed to stencilOperation to specify that stencil value must be replaced */
Constants.REPLACE = 0x1E01;
/** Passed to stencilOperation to specify that stencil value must be incremented */
Constants.INCR = 0x1E02;
/** Passed to stencilOperation to specify that stencil value must be decremented */
Constants.DECR = 0x1E03;
/** Passed to stencilOperation to specify that stencil value must be inverted */
Constants.INVERT = 0x150A;
/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
Constants.INCR_WRAP = 0x8507;
/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
Constants.DECR_WRAP = 0x8508;
/** Texture is not repeating outside of 0..1 UVs */
Constants.TEXTURE_CLAMP_ADDRESSMODE = 0;
/** Texture is repeating outside of 0..1 UVs */
Constants.TEXTURE_WRAP_ADDRESSMODE = 1;
/** Texture is repeating and mirrored */
Constants.TEXTURE_MIRROR_ADDRESSMODE = 2;
/** ALPHA */
Constants.TEXTUREFORMAT_ALPHA = 0;
/** LUMINANCE */
Constants.TEXTUREFORMAT_LUMINANCE = 1;
/** LUMINANCE_ALPHA */
Constants.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
/** RGB */
Constants.TEXTUREFORMAT_RGB = 4;
/** RGBA */
Constants.TEXTUREFORMAT_RGBA = 5;
/** RED */
Constants.TEXTUREFORMAT_RED = 6;
/** RED (2nd reference) */
Constants.TEXTUREFORMAT_R = 6;
/** RG */
Constants.TEXTUREFORMAT_RG = 7;
/** RED_INTEGER */
Constants.TEXTUREFORMAT_RED_INTEGER = 8;
/** RED_INTEGER (2nd reference) */
Constants.TEXTUREFORMAT_R_INTEGER = 8;
/** RG_INTEGER */
Constants.TEXTUREFORMAT_RG_INTEGER = 9;
/** RGB_INTEGER */
Constants.TEXTUREFORMAT_RGB_INTEGER = 10;
/** RGBA_INTEGER */
Constants.TEXTUREFORMAT_RGBA_INTEGER = 11;
/** UNSIGNED_BYTE */
Constants.TEXTURETYPE_UNSIGNED_BYTE = 0;
/** UNSIGNED_BYTE (2nd reference) */
Constants.TEXTURETYPE_UNSIGNED_INT = 0;
/** FLOAT */
Constants.TEXTURETYPE_FLOAT = 1;
/** HALF_FLOAT */
Constants.TEXTURETYPE_HALF_FLOAT = 2;
/** BYTE */
Constants.TEXTURETYPE_BYTE = 3;
/** SHORT */
Constants.TEXTURETYPE_SHORT = 4;
/** UNSIGNED_SHORT */
Constants.TEXTURETYPE_UNSIGNED_SHORT = 5;
/** INT */
Constants.TEXTURETYPE_INT = 6;
/** UNSIGNED_INT */
Constants.TEXTURETYPE_UNSIGNED_INTEGER = 7;
/** UNSIGNED_SHORT_4_4_4_4 */
Constants.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
/** UNSIGNED_SHORT_5_5_5_1 */
Constants.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
/** UNSIGNED_SHORT_5_6_5 */
Constants.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
/** UNSIGNED_INT_2_10_10_10_REV */
Constants.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
/** UNSIGNED_INT_24_8 */
Constants.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
/** UNSIGNED_INT_10F_11F_11F_REV */
Constants.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
/** UNSIGNED_INT_5_9_9_9_REV */
Constants.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
/** FLOAT_32_UNSIGNED_INT_24_8_REV */
Constants.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
/** nearest is mag = nearest and min = nearest and no mip */
Constants.TEXTURE_NEAREST_SAMPLINGMODE = 1;
/** mag = nearest and min = nearest and mip = none */
Constants.TEXTURE_NEAREST_NEAREST = 1;
/** Bilinear is mag = linear and min = linear and no mip */
Constants.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
/** mag = linear and min = linear and mip = none */
Constants.TEXTURE_LINEAR_LINEAR = 2;
/** Trilinear is mag = linear and min = linear and mip = linear */
Constants.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
/** Trilinear is mag = linear and min = linear and mip = linear */
Constants.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
/** mag = nearest and min = nearest and mip = nearest */
Constants.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
/** mag = nearest and min = linear and mip = nearest */
Constants.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
/** mag = nearest and min = linear and mip = linear */
Constants.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
/** mag = nearest and min = linear and mip = none */
Constants.TEXTURE_NEAREST_LINEAR = 7;
/** nearest is mag = nearest and min = nearest and mip = linear */
Constants.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 8;
/** mag = linear and min = nearest and mip = nearest */
Constants.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
/** mag = linear and min = nearest and mip = linear */
Constants.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
/** Bilinear is mag = linear and min = linear and mip = nearest */
Constants.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 11;
/** mag = linear and min = nearest and mip = none */
Constants.TEXTURE_LINEAR_NEAREST = 12;
/** Explicit coordinates mode */
Constants.TEXTURE_EXPLICIT_MODE = 0;
/** Spherical coordinates mode */
Constants.TEXTURE_SPHERICAL_MODE = 1;
/** Planar coordinates mode */
Constants.TEXTURE_PLANAR_MODE = 2;
/** Cubic coordinates mode */
Constants.TEXTURE_CUBIC_MODE = 3;
/** Projection coordinates mode */
Constants.TEXTURE_PROJECTION_MODE = 4;
/** Skybox coordinates mode */
Constants.TEXTURE_SKYBOX_MODE = 5;
/** Inverse Cubic coordinates mode */
Constants.TEXTURE_INVCUBIC_MODE = 6;
/** Equirectangular coordinates mode */
Constants.TEXTURE_EQUIRECTANGULAR_MODE = 7;
/** Equirectangular Fixed coordinates mode */
Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
/** Equirectangular Fixed Mirrored coordinates mode */
Constants.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
/** Offline (baking) quality for texture filtering */
Constants.TEXTURE_FILTERING_QUALITY_OFFLINE = 4096;
/** High quality for texture filtering */
Constants.TEXTURE_FILTERING_QUALITY_HIGH = 64;
/** Medium quality for texture filtering */
Constants.TEXTURE_FILTERING_QUALITY_MEDIUM = 16;
/** Low quality for texture filtering */
Constants.TEXTURE_FILTERING_QUALITY_LOW = 8;
// Texture rescaling mode
/** Defines that texture rescaling will use a floor to find the closer power of 2 size */
Constants.SCALEMODE_FLOOR = 1;
/** Defines that texture rescaling will look for the nearest power of 2 size */
Constants.SCALEMODE_NEAREST = 2;
/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
Constants.SCALEMODE_CEILING = 3;
/**
* The dirty texture flag value
*/
Constants.MATERIAL_TextureDirtyFlag = 1;
/**
* The dirty light flag value
*/
Constants.MATERIAL_LightDirtyFlag = 2;
/**
* The dirty fresnel flag value
*/
Constants.MATERIAL_FresnelDirtyFlag = 4;
/**
* The dirty attribute flag value
*/
Constants.MATERIAL_AttributesDirtyFlag = 8;
/**
* The dirty misc flag value
*/
Constants.MATERIAL_MiscDirtyFlag = 16;
/**
* The all dirty flag value
*/
Constants.MATERIAL_AllDirtyFlag = 31;
/**
* Returns the triangle fill mode
*/
Constants.MATERIAL_TriangleFillMode = 0;
/**
* Returns the wireframe mode
*/
Constants.MATERIAL_WireFrameFillMode = 1;
/**
* Returns the point fill mode
*/
Constants.MATERIAL_PointFillMode = 2;
/**
* Returns the point list draw mode
*/
Constants.MATERIAL_PointListDrawMode = 3;
/**
* Returns the line list draw mode
*/
Constants.MATERIAL_LineListDrawMode = 4;
/**
* Returns the line loop draw mode
*/
Constants.MATERIAL_LineLoopDrawMode = 5;
/**
* Returns the line strip draw mode
*/
Constants.MATERIAL_LineStripDrawMode = 6;
/**
* Returns the triangle strip draw mode
*/
Constants.MATERIAL_TriangleStripDrawMode = 7;
/**
* Returns the triangle fan draw mode
*/
Constants.MATERIAL_TriangleFanDrawMode = 8;
/**
* Stores the clock-wise side orientation
*/
Constants.MATERIAL_ClockWiseSideOrientation = 0;
/**
* Stores the counter clock-wise side orientation
*/
Constants.MATERIAL_CounterClockWiseSideOrientation = 1;
/**
* Nothing
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_NothingTrigger = 0;
/**
* On pick
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnPickTrigger = 1;
/**
* On left pick
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnLeftPickTrigger = 2;
/**
* On right pick
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnRightPickTrigger = 3;
/**
* On center pick
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnCenterPickTrigger = 4;
/**
* On pick down
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnPickDownTrigger = 5;
/**
* On double pick
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnDoublePickTrigger = 6;
/**
* On pick up
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnPickUpTrigger = 7;
/**
* On pick out.
* This trigger will only be raised if you also declared a OnPickDown
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnPickOutTrigger = 16;
/**
* On long press
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnLongPressTrigger = 8;
/**
* On pointer over
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnPointerOverTrigger = 9;
/**
* On pointer out
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnPointerOutTrigger = 10;
/**
* On every frame
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnEveryFrameTrigger = 11;
/**
* On intersection enter
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnIntersectionEnterTrigger = 12;
/**
* On intersection exit
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnIntersectionExitTrigger = 13;
/**
* On key down
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnKeyDownTrigger = 14;
/**
* On key up
* @see https://doc.babylonjs.com/how_to/how_to_use_actions#triggers
*/
Constants.ACTION_OnKeyUpTrigger = 15;
/**
* Billboard mode will only apply to Y axis
*/
Constants.PARTICLES_BILLBOARDMODE_Y = 2;
/**
* Billboard mode will apply to all axes
*/
Constants.PARTICLES_BILLBOARDMODE_ALL = 7;
/**
* Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
*/
Constants.PARTICLES_BILLBOARDMODE_STRETCHED = 8;
/** Default culling strategy : this is an exclusion test and it's the more accurate.
* Test order :
* Is the bounding sphere outside the frustum ?
* If not, are the bounding box vertices outside the frustum ?
* It not, then the cullable object is in the frustum.
*/
Constants.MESHES_CULLINGSTRATEGY_STANDARD = 0;
/** Culling strategy : Bounding Sphere Only.
* This is an exclusion test. It's faster than the standard strategy because the bounding box is not tested.
* It's also less accurate than the standard because some not visible objects can still be selected.
* Test : is the bounding sphere outside the frustum ?
* If not, then the cullable object is in the frustum.
*/
Constants.MESHES_CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
/** Culling strategy : Optimistic Inclusion.
* This in an inclusion test first, then the standard exclusion test.
* This can be faster when a cullable object is expected to be almost always in the camera frustum.
* This could also be a little slower than the standard test when the tested object center is not the frustum but one of its bounding box vertex is still inside.
* Anyway, it's as accurate as the standard strategy.
* Test :
* Is the cullable object bounding sphere center in the frustum ?
* If not, apply the default culling strategy.
*/
Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION = 2;
/** Culling strategy : Optimistic Inclusion then Bounding Sphere Only.
* This in an inclusion test first, then the bounding sphere only exclusion test.
* This can be the fastest test when a cullable object is expected to be almost always in the camera frustum.
* This could also be a little slower than the BoundingSphereOnly strategy when the tested object center is not in the frustum but its bounding sphere still intersects it.
* It's less accurate than the standard strategy and as accurate as the BoundingSphereOnly strategy.
* Test :
* Is the cullable object bounding sphere center in the frustum ?
* If not, apply the Bounding Sphere Only strategy. No Bounding Box is tested here.
*/
Constants.MESHES_CULLINGSTRATEGY_OPTIMISTIC_INCLUSION_THEN_BSPHERE_ONLY = 3;
/**
* No logging while loading
*/
Constants.SCENELOADER_NO_LOGGING = 0;
/**
* Minimal logging while loading
*/
Constants.SCENELOADER_MINIMAL_LOGGING = 1;
/**
* Summary logging while loading
*/
Constants.SCENELOADER_SUMMARY_LOGGING = 2;
/**
* Detailled logging while loading
*/
Constants.SCENELOADER_DETAILED_LOGGING = 3;
/**
* Prepass texture index for color
*/
Constants.PREPASS_COLOR_INDEX = 0;
/**
* Prepass texture index for irradiance
*/
Constants.PREPASS_IRRADIANCE_INDEX = 1;
/**
* Prepass texture index for depth + normal
*/
Constants.PREPASS_DEPTHNORMAL_INDEX = 2;
/**
* Prepass texture index for albedo
*/
Constants.PREPASS_ALBEDO_INDEX = 3;
return Constants;
}());
/***/ }),
/***/ "./Engines/engine.ts":
/*!***************************!*\
!*** ./Engines/engine.ts ***!
\***************************/
/*! exports provided: Engine */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return Engine; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts");
/* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts");
/* harmony import */ var _Misc_performanceMonitor__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Misc/performanceMonitor */ "./Misc/performanceMonitor.ts");
/* harmony import */ var _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/perfCounter */ "./Misc/perfCounter.ts");
/* harmony import */ var _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/WebGL/webGLDataBuffer */ "./Meshes/WebGL/webGLDataBuffer.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Extensions_engine_alpha__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./Extensions/engine.alpha */ "./Engines/Extensions/engine.alpha.ts");
/* harmony import */ var _Extensions_engine_readTexture__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Extensions/engine.readTexture */ "./Engines/Extensions/engine.readTexture.ts");
/* harmony import */ var _Extensions_engine_dynamicBuffer__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Extensions/engine.dynamicBuffer */ "./Engines/Extensions/engine.dynamicBuffer.ts");
/**
* The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
*/
var Engine = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Engine, _super);
/**
* Creates a new engine
* @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
* @param antialias defines enable antialiasing (default: false)
* @param options defines further options to be sent to the getContext() function
* @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
*/
function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
var _this = _super.call(this, canvasOrContext, antialias, options, adaptToDeviceRatio) || this;
// Members
/**
* Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
**/
_this.enableOfflineSupport = false;
/**
* Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (js will always consider the database is up to date)
**/
_this.disableManifestCheck = false;
/**
* Gets the list of created scenes
*/
_this.scenes = new Array();
/**
* Event raised when a new scene is created
*/
_this.onNewSceneAddedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Gets the list of created postprocesses
*/
_this.postProcesses = new Array();
/**
* Gets a boolean indicating if the pointer is currently locked
*/
_this.isPointerLock = false;
// Observables
/**
* Observable event triggered each time the rendering canvas is resized
*/
_this.onResizeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered each time the canvas loses focus
*/
_this.onCanvasBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered each time the canvas gains focus
*/
_this.onCanvasFocusObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable event triggered each time the canvas receives pointerout event
*/
_this.onCanvasPointerOutObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable raised when the engine begins a new frame
*/
_this.onBeginFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* If set, will be used to request the next animation frame for the render loop
*/
_this.customAnimationFrameRequester = null;
/**
* Observable raised when the engine ends the current frame
*/
_this.onEndFrameObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable raised when the engine is about to compile a shader
*/
_this.onBeforeShaderCompilationObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable raised when the engine has jsut compiled a shader
*/
_this.onAfterShaderCompilationObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
// Deterministic lockstepMaxSteps
_this._deterministicLockstep = false;
_this._lockstepMaxSteps = 4;
_this._timeStep = 1 / 60;
// FPS
_this._fps = 60;
_this._deltaTime = 0;
/** @hidden */
_this._drawCalls = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_8__["PerfCounter"]();
/** Gets or sets the tab index to set to the rendering canvas. 1 is the minimum value to set to be able to capture keyboard events */
_this.canvasTabIndex = 1;
/**
* Turn this value on if you want to pause FPS computation when in background
*/
_this.disablePerformanceMonitorInBackground = false;
_this._performanceMonitor = new _Misc_performanceMonitor__WEBPACK_IMPORTED_MODULE_7__["PerformanceMonitor"]();
Engine.Instances.push(_this);
if (!canvasOrContext) {
return _this;
}
options = _this._creationOptions;
if (canvasOrContext.getContext) {
var canvas_1 = canvasOrContext;
_this._onCanvasFocus = function () {
_this.onCanvasFocusObservable.notifyObservers(_this);
};
_this._onCanvasBlur = function () {
_this.onCanvasBlurObservable.notifyObservers(_this);
};
canvas_1.addEventListener("focus", _this._onCanvasFocus);
canvas_1.addEventListener("blur", _this._onCanvasBlur);
_this._onBlur = function () {
if (_this.disablePerformanceMonitorInBackground) {
_this._performanceMonitor.disable();
}
_this._windowIsBackground = true;
};
_this._onFocus = function () {
if (_this.disablePerformanceMonitorInBackground) {
_this._performanceMonitor.enable();
}
_this._windowIsBackground = false;
};
_this._onCanvasPointerOut = function (ev) {
_this.onCanvasPointerOutObservable.notifyObservers(ev);
};
canvas_1.addEventListener("pointerout", _this._onCanvasPointerOut);
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) {
var hostWindow = _this.getHostWindow();
hostWindow.addEventListener("blur", _this._onBlur);
hostWindow.addEventListener("focus", _this._onFocus);
var anyDoc_1 = document;
// Fullscreen
_this._onFullscreenChange = function () {
if (anyDoc_1.fullscreen !== undefined) {
_this.isFullscreen = anyDoc_1.fullscreen;
}
else if (anyDoc_1.mozFullScreen !== undefined) {
_this.isFullscreen = anyDoc_1.mozFullScreen;
}
else if (anyDoc_1.webkitIsFullScreen !== undefined) {
_this.isFullscreen = anyDoc_1.webkitIsFullScreen;
}
else if (anyDoc_1.msIsFullScreen !== undefined) {
_this.isFullscreen = anyDoc_1.msIsFullScreen;
}
// Pointer lock
if (_this.isFullscreen && _this._pointerLockRequested && canvas_1) {
Engine._RequestPointerlock(canvas_1);
}
};
document.addEventListener("fullscreenchange", _this._onFullscreenChange, false);
document.addEventListener("mozfullscreenchange", _this._onFullscreenChange, false);
document.addEventListener("webkitfullscreenchange", _this._onFullscreenChange, false);
document.addEventListener("msfullscreenchange", _this._onFullscreenChange, false);
// Pointer lock
_this._onPointerLockChange = function () {
_this.isPointerLock = (anyDoc_1.mozPointerLockElement === canvas_1 ||
anyDoc_1.webkitPointerLockElement === canvas_1 ||
anyDoc_1.msPointerLockElement === canvas_1 ||
anyDoc_1.pointerLockElement === canvas_1);
};
document.addEventListener("pointerlockchange", _this._onPointerLockChange, false);
document.addEventListener("mspointerlockchange", _this._onPointerLockChange, false);
document.addEventListener("mozpointerlockchange", _this._onPointerLockChange, false);
document.addEventListener("webkitpointerlockchange", _this._onPointerLockChange, false);
// Create Audio Engine if needed.
if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
Engine.audioEngine = Engine.AudioEngineFactory(_this.getRenderingCanvas());
}
}
_this._connectVREvents();
_this.enableOfflineSupport = Engine.OfflineProviderFactory !== undefined;
if (!options.doNotHandleTouchAction) {
_this._disableTouchAction();
}
_this._deterministicLockstep = !!options.deterministicLockstep;
_this._lockstepMaxSteps = options.lockstepMaxSteps || 0;
_this._timeStep = options.timeStep || 1 / 60;
}
// Load WebVR Devices
_this._prepareVRComponent();
if (options.autoEnableWebVR) {
_this.initWebVR();
}
return _this;
}
Object.defineProperty(Engine, "NpmPackage", {
/**
* Returns the current npm package of the sdk
*/
// Not mixed with Version for tooling purpose.
get: function () {
return _thinEngine__WEBPACK_IMPORTED_MODULE_5__["ThinEngine"].NpmPackage;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine, "Version", {
/**
* Returns the current version of the framework
*/
get: function () {
return _thinEngine__WEBPACK_IMPORTED_MODULE_5__["ThinEngine"].Version;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine, "Instances", {
/** Gets the list of created engines */
get: function () {
return _engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].Instances;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine, "LastCreatedEngine", {
/**
* Gets the latest created engine
*/
get: function () {
return _engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedEngine;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine, "LastCreatedScene", {
/**
* Gets the latest created scene
*/
get: function () {
return _engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedScene;
},
enumerable: false,
configurable: true
});
/**
* Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
* @param flag defines which part of the materials must be marked as dirty
* @param predicate defines a predicate used to filter which materials should be affected
*/
Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
var engine = Engine.Instances[engineIndex];
for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
}
}
};
/**
* Method called to create the default loading screen.
* This can be overriden in your own app.
* @param canvas The rendering canvas element
* @returns The loading screen
*/
Engine.DefaultLoadingScreenFactory = function (canvas) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_4__["_DevTools"].WarnImport("LoadingScreen");
};
Object.defineProperty(Engine.prototype, "_supportsHardwareTextureRescaling", {
get: function () {
return !!Engine._RescalePostProcessFactory;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "performanceMonitor", {
/**
* Gets the performance monitor attached to this engine
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
*/
get: function () {
return this._performanceMonitor;
},
enumerable: false,
configurable: true
});
// Events
/**
* Gets the HTML element used to attach event listeners
* @returns a HTML element
*/
Engine.prototype.getInputElement = function () {
return this._renderingCanvas;
};
/**
* Gets current aspect ratio
* @param viewportOwner defines the camera to use to get the aspect ratio
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the aspect ratio
*/
Engine.prototype.getAspectRatio = function (viewportOwner, useScreen) {
if (useScreen === void 0) { useScreen = false; }
var viewport = viewportOwner.viewport;
return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
};
/**
* Gets current screen aspect ratio
* @returns a number defining the aspect ratio
*/
Engine.prototype.getScreenAspectRatio = function () {
return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
};
/**
* Gets the client rect of the HTML canvas attached with the current webGL context
* @returns a client rectanglee
*/
Engine.prototype.getRenderingCanvasClientRect = function () {
if (!this._renderingCanvas) {
return null;
}
return this._renderingCanvas.getBoundingClientRect();
};
/**
* Gets the client rect of the HTML element used for events
* @returns a client rectanglee
*/
Engine.prototype.getInputElementClientRect = function () {
if (!this._renderingCanvas) {
return null;
}
return this.getInputElement().getBoundingClientRect();
};
/**
* Gets a boolean indicating that the engine is running in deterministic lock step mode
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
* @returns true if engine is in deterministic lock step mode
*/
Engine.prototype.isDeterministicLockStep = function () {
return this._deterministicLockstep;
};
/**
* Gets the max steps when engine is running in deterministic lock step
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
* @returns the max steps
*/
Engine.prototype.getLockstepMaxSteps = function () {
return this._lockstepMaxSteps;
};
/**
* Returns the time in ms between steps when using deterministic lock step.
* @returns time step in (ms)
*/
Engine.prototype.getTimeStep = function () {
return this._timeStep * 1000;
};
/**
* Force the mipmap generation for the given render target texture
* @param texture defines the render target texture to use
* @param unbind defines whether or not to unbind the texture after generation. Defaults to true.
*/
Engine.prototype.generateMipMapsForCubemap = function (texture, unbind) {
if (unbind === void 0) { unbind = true; }
if (texture.generateMipMaps) {
var gl = this._gl;
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
if (unbind) {
this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
}
}
};
/** States */
/**
* Set various states to the webGL context
* @param culling defines backface culling state
* @param zOffset defines the value to apply to zOffset (0 by default)
* @param force defines if states must be applied even if cache is up to date
* @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
*/
Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
if (zOffset === void 0) { zOffset = 0; }
if (reverseSide === void 0) { reverseSide = false; }
// Culling
if (this._depthCullingState.cull !== culling || force) {
this._depthCullingState.cull = culling;
}
// Cull face
var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
if (this._depthCullingState.cullFace !== cullFace || force) {
this._depthCullingState.cullFace = cullFace;
}
// Z offset
this.setZOffset(zOffset);
// Front face
var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
if (this._depthCullingState.frontFace !== frontFace || force) {
this._depthCullingState.frontFace = frontFace;
}
};
/**
* Set the z offset to apply to current rendering
* @param value defines the offset to apply
*/
Engine.prototype.setZOffset = function (value) {
this._depthCullingState.zOffset = value;
};
/**
* Gets the current value of the zOffset
* @returns the current zOffset state
*/
Engine.prototype.getZOffset = function () {
return this._depthCullingState.zOffset;
};
/**
* Enable or disable depth buffering
* @param enable defines the state to set
*/
Engine.prototype.setDepthBuffer = function (enable) {
this._depthCullingState.depthTest = enable;
};
/**
* Gets a boolean indicating if depth writing is enabled
* @returns the current depth writing state
*/
Engine.prototype.getDepthWrite = function () {
return this._depthCullingState.depthMask;
};
/**
* Enable or disable depth writing
* @param enable defines the state to set
*/
Engine.prototype.setDepthWrite = function (enable) {
this._depthCullingState.depthMask = enable;
};
/**
* Gets a boolean indicating if stencil buffer is enabled
* @returns the current stencil buffer state
*/
Engine.prototype.getStencilBuffer = function () {
return this._stencilState.stencilTest;
};
/**
* Enable or disable the stencil buffer
* @param enable defines if the stencil buffer must be enabled or disabled
*/
Engine.prototype.setStencilBuffer = function (enable) {
this._stencilState.stencilTest = enable;
};
/**
* Gets the current stencil mask
* @returns a number defining the new stencil mask to use
*/
Engine.prototype.getStencilMask = function () {
return this._stencilState.stencilMask;
};
/**
* Sets the current stencil mask
* @param mask defines the new stencil mask to use
*/
Engine.prototype.setStencilMask = function (mask) {
this._stencilState.stencilMask = mask;
};
/**
* Gets the current stencil function
* @returns a number defining the stencil function to use
*/
Engine.prototype.getStencilFunction = function () {
return this._stencilState.stencilFunc;
};
/**
* Gets the current stencil reference value
* @returns a number defining the stencil reference value to use
*/
Engine.prototype.getStencilFunctionReference = function () {
return this._stencilState.stencilFuncRef;
};
/**
* Gets the current stencil mask
* @returns a number defining the stencil mask to use
*/
Engine.prototype.getStencilFunctionMask = function () {
return this._stencilState.stencilFuncMask;
};
/**
* Sets the current stencil function
* @param stencilFunc defines the new stencil function to use
*/
Engine.prototype.setStencilFunction = function (stencilFunc) {
this._stencilState.stencilFunc = stencilFunc;
};
/**
* Sets the current stencil reference
* @param reference defines the new stencil reference to use
*/
Engine.prototype.setStencilFunctionReference = function (reference) {
this._stencilState.stencilFuncRef = reference;
};
/**
* Sets the current stencil mask
* @param mask defines the new stencil mask to use
*/
Engine.prototype.setStencilFunctionMask = function (mask) {
this._stencilState.stencilFuncMask = mask;
};
/**
* Gets the current stencil operation when stencil fails
* @returns a number defining stencil operation to use when stencil fails
*/
Engine.prototype.getStencilOperationFail = function () {
return this._stencilState.stencilOpStencilFail;
};
/**
* Gets the current stencil operation when depth fails
* @returns a number defining stencil operation to use when depth fails
*/
Engine.prototype.getStencilOperationDepthFail = function () {
return this._stencilState.stencilOpDepthFail;
};
/**
* Gets the current stencil operation when stencil passes
* @returns a number defining stencil operation to use when stencil passes
*/
Engine.prototype.getStencilOperationPass = function () {
return this._stencilState.stencilOpStencilDepthPass;
};
/**
* Sets the stencil operation to use when stencil fails
* @param operation defines the stencil operation to use when stencil fails
*/
Engine.prototype.setStencilOperationFail = function (operation) {
this._stencilState.stencilOpStencilFail = operation;
};
/**
* Sets the stencil operation to use when depth fails
* @param operation defines the stencil operation to use when depth fails
*/
Engine.prototype.setStencilOperationDepthFail = function (operation) {
this._stencilState.stencilOpDepthFail = operation;
};
/**
* Sets the stencil operation to use when stencil passes
* @param operation defines the stencil operation to use when stencil passes
*/
Engine.prototype.setStencilOperationPass = function (operation) {
this._stencilState.stencilOpStencilDepthPass = operation;
};
/**
* Sets a boolean indicating if the dithering state is enabled or disabled
* @param value defines the dithering state
*/
Engine.prototype.setDitheringState = function (value) {
if (value) {
this._gl.enable(this._gl.DITHER);
}
else {
this._gl.disable(this._gl.DITHER);
}
};
/**
* Sets a boolean indicating if the rasterizer state is enabled or disabled
* @param value defines the rasterizer state
*/
Engine.prototype.setRasterizerState = function (value) {
if (value) {
this._gl.disable(this._gl.RASTERIZER_DISCARD);
}
else {
this._gl.enable(this._gl.RASTERIZER_DISCARD);
}
};
/**
* Gets the current depth function
* @returns a number defining the depth function
*/
Engine.prototype.getDepthFunction = function () {
return this._depthCullingState.depthFunc;
};
/**
* Sets the current depth function
* @param depthFunc defines the function to use
*/
Engine.prototype.setDepthFunction = function (depthFunc) {
this._depthCullingState.depthFunc = depthFunc;
};
/**
* Sets the current depth function to GREATER
*/
Engine.prototype.setDepthFunctionToGreater = function () {
this._depthCullingState.depthFunc = this._gl.GREATER;
};
/**
* Sets the current depth function to GEQUAL
*/
Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
this._depthCullingState.depthFunc = this._gl.GEQUAL;
};
/**
* Sets the current depth function to LESS
*/
Engine.prototype.setDepthFunctionToLess = function () {
this._depthCullingState.depthFunc = this._gl.LESS;
};
/**
* Sets the current depth function to LEQUAL
*/
Engine.prototype.setDepthFunctionToLessOrEqual = function () {
this._depthCullingState.depthFunc = this._gl.LEQUAL;
};
/**
* Caches the the state of the stencil buffer
*/
Engine.prototype.cacheStencilState = function () {
this._cachedStencilBuffer = this.getStencilBuffer();
this._cachedStencilFunction = this.getStencilFunction();
this._cachedStencilMask = this.getStencilMask();
this._cachedStencilOperationPass = this.getStencilOperationPass();
this._cachedStencilOperationFail = this.getStencilOperationFail();
this._cachedStencilOperationDepthFail = this.getStencilOperationDepthFail();
this._cachedStencilReference = this.getStencilFunctionReference();
};
/**
* Restores the state of the stencil buffer
*/
Engine.prototype.restoreStencilState = function () {
this.setStencilFunction(this._cachedStencilFunction);
this.setStencilMask(this._cachedStencilMask);
this.setStencilBuffer(this._cachedStencilBuffer);
this.setStencilOperationPass(this._cachedStencilOperationPass);
this.setStencilOperationFail(this._cachedStencilOperationFail);
this.setStencilOperationDepthFail(this._cachedStencilOperationDepthFail);
this.setStencilFunctionReference(this._cachedStencilReference);
};
/**
* Directly set the WebGL Viewport
* @param x defines the x coordinate of the viewport (in screen space)
* @param y defines the y coordinate of the viewport (in screen space)
* @param width defines the width of the viewport (in screen space)
* @param height defines the height of the viewport (in screen space)
* @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state
*/
Engine.prototype.setDirectViewport = function (x, y, width, height) {
var currentViewport = this._cachedViewport;
this._cachedViewport = null;
this._viewport(x, y, width, height);
return currentViewport;
};
/**
* Executes a scissor clear (ie. a clear on a specific portion of the screen)
* @param x defines the x-coordinate of the top left corner of the clear rectangle
* @param y defines the y-coordinate of the corner of the clear rectangle
* @param width defines the width of the clear rectangle
* @param height defines the height of the clear rectangle
* @param clearColor defines the clear color
*/
Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
this.enableScissor(x, y, width, height);
this.clear(clearColor, true, true, true);
this.disableScissor();
};
/**
* Enable scissor test on a specific rectangle (ie. render will only be executed on a specific portion of the screen)
* @param x defines the x-coordinate of the top left corner of the clear rectangle
* @param y defines the y-coordinate of the corner of the clear rectangle
* @param width defines the width of the clear rectangle
* @param height defines the height of the clear rectangle
*/
Engine.prototype.enableScissor = function (x, y, width, height) {
var gl = this._gl;
// Change state
gl.enable(gl.SCISSOR_TEST);
gl.scissor(x, y, width, height);
};
/**
* Disable previously set scissor test rectangle
*/
Engine.prototype.disableScissor = function () {
var gl = this._gl;
gl.disable(gl.SCISSOR_TEST);
};
Engine.prototype._reportDrawCall = function () {
this._drawCalls.addCount(1, false);
};
/**
* Initializes a webVR display and starts listening to display change events
* The onVRDisplayChangedObservable will be notified upon these changes
* @returns The onVRDisplayChangedObservable
*/
Engine.prototype.initWebVR = function () {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_4__["_DevTools"].WarnImport("WebVRCamera");
};
/** @hidden */
Engine.prototype._prepareVRComponent = function () {
// Do nothing as the engine side effect will overload it
};
/** @hidden */
Engine.prototype._connectVREvents = function (canvas, document) {
// Do nothing as the engine side effect will overload it
};
/** @hidden */
Engine.prototype._submitVRFrame = function () {
// Do nothing as the engine side effect will overload it
};
/**
* Call this function to leave webVR mode
* Will do nothing if webVR is not supported or if there is no webVR device
* @see https://doc.babylonjs.com/how_to/webvr_camera
*/
Engine.prototype.disableVR = function () {
// Do nothing as the engine side effect will overload it
};
/**
* Gets a boolean indicating that the system is in VR mode and is presenting
* @returns true if VR mode is engaged
*/
Engine.prototype.isVRPresenting = function () {
return false;
};
/** @hidden */
Engine.prototype._requestVRFrame = function () {
// Do nothing as the engine side effect will overload it
};
/** @hidden */
Engine.prototype._loadFileAsync = function (url, offlineProvider, useArrayBuffer) {
var _this = this;
return new Promise(function (resolve, reject) {
_this._loadFile(url, function (data) {
resolve(data);
}, undefined, offlineProvider, useArrayBuffer, function (request, exception) {
reject(exception);
});
});
};
/**
* Gets the source code of the vertex shader associated with a specific webGL program
* @param program defines the program to use
* @returns a string containing the source code of the vertex shader associated with the program
*/
Engine.prototype.getVertexShaderSource = function (program) {
var shaders = this._gl.getAttachedShaders(program);
if (!shaders) {
return null;
}
return this._gl.getShaderSource(shaders[0]);
};
/**
* Gets the source code of the fragment shader associated with a specific webGL program
* @param program defines the program to use
* @returns a string containing the source code of the fragment shader associated with the program
*/
Engine.prototype.getFragmentShaderSource = function (program) {
var shaders = this._gl.getAttachedShaders(program);
if (!shaders) {
return null;
}
return this._gl.getShaderSource(shaders[1]);
};
/**
* Sets a depth stencil texture from a render target to the according uniform.
* @param channel The texture channel
* @param uniform The uniform to set
* @param texture The render target texture containing the depth stencil texture to apply
*/
Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
if (channel === undefined) {
return;
}
if (uniform) {
this._boundUniforms[channel] = uniform;
}
if (!texture || !texture.depthStencilTexture) {
this._setTexture(channel, null);
}
else {
this._setTexture(channel, texture, false, true);
}
};
/**
* Sets a texture to the webGL context from a postprocess
* @param channel defines the channel to use
* @param postProcess defines the source postprocess
*/
Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
};
/**
* Binds the output of the passed in post process to the texture channel specified
* @param channel The channel the texture should be bound to
* @param postProcess The post process which's output should be bound
*/
Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
};
Engine.prototype._rebuildBuffers = function () {
// Index / Vertex
for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
var scene = _a[_i];
scene.resetCachedMaterial();
scene._rebuildGeometries();
scene._rebuildTextures();
}
_super.prototype._rebuildBuffers.call(this);
};
/** @hidden */
Engine.prototype._renderFrame = function () {
for (var index = 0; index < this._activeRenderLoops.length; index++) {
var renderFunction = this._activeRenderLoops[index];
renderFunction();
}
};
Engine.prototype._renderLoop = function () {
if (!this._contextWasLost) {
var shouldRender = true;
if (!this.renderEvenInBackground && this._windowIsBackground) {
shouldRender = false;
}
if (shouldRender) {
// Start new frame
this.beginFrame();
// Child canvases
if (!this._renderViews()) {
// Main frame
this._renderFrame();
}
// Present
this.endFrame();
}
}
if (this._activeRenderLoops.length > 0) {
// Register new frame
if (this.customAnimationFrameRequester) {
this.customAnimationFrameRequester.requestID = this._queueNewFrame(this.customAnimationFrameRequester.renderFunction || this._boundRenderFunction, this.customAnimationFrameRequester);
this._frameHandler = this.customAnimationFrameRequester.requestID;
}
else if (this.isVRPresenting()) {
this._requestVRFrame();
}
else {
this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
}
}
else {
this._renderingQueueLaunched = false;
}
};
/** @hidden */
Engine.prototype._renderViews = function () {
return false;
};
/**
* Toggle full screen mode
* @param requestPointerLock defines if a pointer lock should be requested from the user
*/
Engine.prototype.switchFullscreen = function (requestPointerLock) {
if (this.isFullscreen) {
this.exitFullscreen();
}
else {
this.enterFullscreen(requestPointerLock);
}
};
/**
* Enters full screen mode
* @param requestPointerLock defines if a pointer lock should be requested from the user
*/
Engine.prototype.enterFullscreen = function (requestPointerLock) {
if (!this.isFullscreen) {
this._pointerLockRequested = requestPointerLock;
if (this._renderingCanvas) {
Engine._RequestFullscreen(this._renderingCanvas);
}
}
};
/**
* Exits full screen mode
*/
Engine.prototype.exitFullscreen = function () {
if (this.isFullscreen) {
Engine._ExitFullscreen();
}
};
/**
* Enters Pointerlock mode
*/
Engine.prototype.enterPointerlock = function () {
if (this._renderingCanvas) {
Engine._RequestPointerlock(this._renderingCanvas);
}
};
/**
* Exits Pointerlock mode
*/
Engine.prototype.exitPointerlock = function () {
Engine._ExitPointerlock();
};
/**
* Begin a new frame
*/
Engine.prototype.beginFrame = function () {
this._measureFps();
this.onBeginFrameObservable.notifyObservers(this);
_super.prototype.beginFrame.call(this);
};
/**
* Enf the current frame
*/
Engine.prototype.endFrame = function () {
_super.prototype.endFrame.call(this);
this._submitVRFrame();
this.onEndFrameObservable.notifyObservers(this);
};
Engine.prototype.resize = function () {
// We're not resizing the size of the canvas while in VR mode & presenting
if (this.isVRPresenting()) {
return;
}
_super.prototype.resize.call(this);
};
/**
* Force a specific size of the canvas
* @param width defines the new canvas' width
* @param height defines the new canvas' height
* @returns true if the size was changed
*/
Engine.prototype.setSize = function (width, height) {
if (!this._renderingCanvas) {
return false;
}
if (!_super.prototype.setSize.call(this, width, height)) {
return false;
}
if (this.scenes) {
for (var index = 0; index < this.scenes.length; index++) {
var scene = this.scenes[index];
for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
var cam = scene.cameras[camIndex];
cam._currentRenderId = 0;
}
}
if (this.onResizeObservable.hasObservers()) {
this.onResizeObservable.notifyObservers(this);
}
}
return true;
};
Engine.prototype._deletePipelineContext = function (pipelineContext) {
var webGLPipelineContext = pipelineContext;
if (webGLPipelineContext && webGLPipelineContext.program) {
if (webGLPipelineContext.transformFeedback) {
this.deleteTransformFeedback(webGLPipelineContext.transformFeedback);
webGLPipelineContext.transformFeedback = null;
}
}
_super.prototype._deletePipelineContext.call(this, pipelineContext);
};
Engine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
context = context || this._gl;
this.onBeforeShaderCompilationObservable.notifyObservers(this);
var program = _super.prototype.createShaderProgram.call(this, pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings);
this.onAfterShaderCompilationObservable.notifyObservers(this);
return program;
};
Engine.prototype._createShaderProgram = function (pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
var shaderProgram = context.createProgram();
pipelineContext.program = shaderProgram;
if (!shaderProgram) {
throw new Error("Unable to create program");
}
context.attachShader(shaderProgram, vertexShader);
context.attachShader(shaderProgram, fragmentShader);
if (this.webGLVersion > 1 && transformFeedbackVaryings) {
var transformFeedback = this.createTransformFeedback();
this.bindTransformFeedback(transformFeedback);
this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
pipelineContext.transformFeedback = transformFeedback;
}
context.linkProgram(shaderProgram);
if (this.webGLVersion > 1 && transformFeedbackVaryings) {
this.bindTransformFeedback(null);
}
pipelineContext.context = context;
pipelineContext.vertexShader = vertexShader;
pipelineContext.fragmentShader = fragmentShader;
if (!pipelineContext.isParallelCompiled) {
this._finalizePipelineContext(pipelineContext);
}
return shaderProgram;
};
Engine.prototype._releaseTexture = function (texture) {
_super.prototype._releaseTexture.call(this, texture);
// Set output texture of post process to null if the texture has been released/disposed
this.scenes.forEach(function (scene) {
scene.postProcesses.forEach(function (postProcess) {
if (postProcess._outputTexture == texture) {
postProcess._outputTexture = null;
}
});
scene.cameras.forEach(function (camera) {
camera._postProcesses.forEach(function (postProcess) {
if (postProcess) {
if (postProcess._outputTexture == texture) {
postProcess._outputTexture = null;
}
}
});
});
});
};
/**
* @hidden
* Rescales a texture
* @param source input texutre
* @param destination destination texture
* @param scene scene to use to render the resize
* @param internalFormat format to use when resizing
* @param onComplete callback to be called when resize has completed
*/
Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
var _this = this;
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, this._gl.LINEAR);
this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
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);
var rtt = this.createRenderTargetTexture({
width: destination.width,
height: destination.height,
}, {
generateMipMaps: false,
type: _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INT,
samplingMode: _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE,
generateDepthBuffer: false,
generateStencilBuffer: false
});
if (!this._rescalePostProcess && Engine._RescalePostProcessFactory) {
this._rescalePostProcess = Engine._RescalePostProcessFactory(this);
}
this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
_this._rescalePostProcess.onApply = function (effect) {
effect._bindTexture("textureSampler", source);
};
var hostingScene = scene;
if (!hostingScene) {
hostingScene = _this.scenes[_this.scenes.length - 1];
}
hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
_this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
_this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
_this.unBindFramebuffer(rtt);
_this._releaseTexture(rtt);
if (onComplete) {
onComplete();
}
});
};
// FPS
/**
* Gets the current framerate
* @returns a number representing the framerate
*/
Engine.prototype.getFps = function () {
return this._fps;
};
/**
* Gets the time spent between current and previous frame
* @returns a number representing the delta time in ms
*/
Engine.prototype.getDeltaTime = function () {
return this._deltaTime;
};
Engine.prototype._measureFps = function () {
this._performanceMonitor.sampleFrame();
this._fps = this._performanceMonitor.averageFPS;
this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
};
/** @hidden */
Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
var gl = this._gl;
var textureType = this._getWebGLTextureType(texture.type);
var format = this._getInternalFormat(texture.format);
var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
this._bindTextureDirectly(bindTarget, texture, true);
this._unpackFlipY(texture.invertY);
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
gl.texImage2D(target, lod, internalFormat, format, textureType, image);
this._bindTextureDirectly(bindTarget, null, true);
};
/**
* Updates the sample count of a render target texture
* @see https://doc.babylonjs.com/features/webgl2#multisample-render-targets
* @param texture defines the texture to update
* @param samples defines the sample count to set
* @returns the effective sample count (could be 0 if multisample render targets are not supported)
*/
Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
if (this.webGLVersion < 2 || !texture) {
return 1;
}
if (texture.samples === samples) {
return samples;
}
var gl = this._gl;
samples = Math.min(samples, this.getCaps().maxMSAASamples);
// Dispose previous render buffers
if (texture._depthStencilBuffer) {
gl.deleteRenderbuffer(texture._depthStencilBuffer);
texture._depthStencilBuffer = null;
}
if (texture._MSAAFramebuffer) {
gl.deleteFramebuffer(texture._MSAAFramebuffer);
texture._MSAAFramebuffer = null;
}
if (texture._MSAARenderBuffer) {
gl.deleteRenderbuffer(texture._MSAARenderBuffer);
texture._MSAARenderBuffer = null;
}
if (samples > 1 && gl.renderbufferStorageMultisample) {
var framebuffer = gl.createFramebuffer();
if (!framebuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
texture._MSAAFramebuffer = framebuffer;
this._bindUnboundFramebuffer(texture._MSAAFramebuffer);
var colorRenderbuffer = gl.createRenderbuffer();
if (!colorRenderbuffer) {
throw new Error("Unable to create multi sampled framebuffer");
}
gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
texture._MSAARenderBuffer = colorRenderbuffer;
}
else {
this._bindUnboundFramebuffer(texture._framebuffer);
}
texture.samples = samples;
texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
this._bindUnboundFramebuffer(null);
return samples;
};
/**
* Updates a depth texture Comparison Mode and Function.
* If the comparison Function is equal to 0, the mode will be set to none.
* Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
* @param texture The texture to set the comparison function for
* @param comparisonFunction The comparison function to set, 0 if no comparison required
*/
Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
if (this.webGLVersion === 1) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_10__["Logger"].Error("WebGL 1 does not support texture comparison.");
return;
}
var gl = this._gl;
if (texture.isCube) {
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
if (comparisonFunction === 0) {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].LEQUAL);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
}
else {
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
}
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
}
else {
this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
if (comparisonFunction === 0) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].LEQUAL);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
}
else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
}
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
}
texture._comparisonFunction = comparisonFunction;
};
/**
* Creates a webGL buffer to use with instanciation
* @param capacity defines the size of the buffer
* @returns the webGL buffer
*/
Engine.prototype.createInstancesBuffer = function (capacity) {
var buffer = this._gl.createBuffer();
if (!buffer) {
throw new Error("Unable to create instance buffer");
}
var result = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_9__["WebGLDataBuffer"](buffer);
result.capacity = capacity;
this.bindArrayBuffer(result);
this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
return result;
};
/**
* Delete a webGL buffer used with instanciation
* @param buffer defines the webGL buffer to delete
*/
Engine.prototype.deleteInstancesBuffer = function (buffer) {
this._gl.deleteBuffer(buffer);
};
Engine.prototype._clientWaitAsync = function (sync, flags, interval_ms) {
if (flags === void 0) { flags = 0; }
if (interval_ms === void 0) { interval_ms = 10; }
var gl = this._gl;
return new Promise(function (resolve, reject) {
var check = function () {
var res = gl.clientWaitSync(sync, flags, 0);
if (res == gl.WAIT_FAILED) {
reject();
return;
}
if (res == gl.TIMEOUT_EXPIRED) {
setTimeout(check, interval_ms);
return;
}
resolve();
};
check();
});
};
/** @hidden */
Engine.prototype._readPixelsAsync = function (x, y, w, h, format, type, outputBuffer) {
if (this._webGLVersion < 2) {
throw new Error("_readPixelsAsync only work on WebGL2+");
}
var gl = this._gl;
var buf = gl.createBuffer();
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);
gl.bufferData(gl.PIXEL_PACK_BUFFER, outputBuffer.byteLength, gl.STREAM_READ);
gl.readPixels(x, y, w, h, format, type, 0);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
if (!sync) {
return null;
}
gl.flush();
return this._clientWaitAsync(sync, 0, 10).then(function () {
gl.deleteSync(sync);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buf);
gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, outputBuffer);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
gl.deleteBuffer(buf);
return outputBuffer;
});
};
Engine.prototype.dispose = function () {
this.hideLoadingUI();
this.onNewSceneAddedObservable.clear();
// Release postProcesses
while (this.postProcesses.length) {
this.postProcesses[0].dispose();
}
// Rescale PP
if (this._rescalePostProcess) {
this._rescalePostProcess.dispose();
}
// Release scenes
while (this.scenes.length) {
this.scenes[0].dispose();
}
// Release audio engine
if (Engine.Instances.length === 1 && Engine.audioEngine) {
Engine.audioEngine.dispose();
}
//WebVR
this.disableVR();
// Events
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) {
window.removeEventListener("blur", this._onBlur);
window.removeEventListener("focus", this._onFocus);
if (this._renderingCanvas) {
this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
}
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsDocumentAvailable()) {
document.removeEventListener("fullscreenchange", this._onFullscreenChange);
document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
document.removeEventListener("pointerlockchange", this._onPointerLockChange);
document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
}
}
_super.prototype.dispose.call(this);
// Remove from Instances
var index = Engine.Instances.indexOf(this);
if (index >= 0) {
Engine.Instances.splice(index, 1);
}
// Observables
this.onResizeObservable.clear();
this.onCanvasBlurObservable.clear();
this.onCanvasFocusObservable.clear();
this.onCanvasPointerOutObservable.clear();
this.onBeginFrameObservable.clear();
this.onEndFrameObservable.clear();
};
Engine.prototype._disableTouchAction = function () {
if (!this._renderingCanvas || !this._renderingCanvas.setAttribute) {
return;
}
this._renderingCanvas.setAttribute("touch-action", "none");
this._renderingCanvas.style.touchAction = "none";
this._renderingCanvas.style.msTouchAction = "none";
};
// Loading screen
/**
* Display the loading screen
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
Engine.prototype.displayLoadingUI = function () {
if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) {
return;
}
var loadingScreen = this.loadingScreen;
if (loadingScreen) {
loadingScreen.displayLoadingUI();
}
};
/**
* Hide the loading screen
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
Engine.prototype.hideLoadingUI = function () {
if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_2__["DomManagement"].IsWindowObjectExist()) {
return;
}
var loadingScreen = this._loadingScreen;
if (loadingScreen) {
loadingScreen.hideLoadingUI();
}
};
Object.defineProperty(Engine.prototype, "loadingScreen", {
/**
* Gets the current loading screen object
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
get: function () {
if (!this._loadingScreen && this._renderingCanvas) {
this._loadingScreen = Engine.DefaultLoadingScreenFactory(this._renderingCanvas);
}
return this._loadingScreen;
},
/**
* Sets the current loading screen object
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
set: function (loadingScreen) {
this._loadingScreen = loadingScreen;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "loadingUIText", {
/**
* Sets the current loading screen text
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
set: function (text) {
this.loadingScreen.loadingUIText = text;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
/**
* Sets the current loading screen background color
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
set: function (color) {
this.loadingScreen.loadingUIBackgroundColor = color;
},
enumerable: false,
configurable: true
});
/** Pointerlock and fullscreen */
/**
* Ask the browser to promote the current element to pointerlock mode
* @param element defines the DOM element to promote
*/
Engine._RequestPointerlock = function (element) {
element.requestPointerLock = element.requestPointerLock || element.msRequestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
if (element.requestPointerLock) {
element.requestPointerLock();
}
};
/**
* Asks the browser to exit pointerlock mode
*/
Engine._ExitPointerlock = function () {
var anyDoc = document;
document.exitPointerLock = document.exitPointerLock || anyDoc.msExitPointerLock || anyDoc.mozExitPointerLock || anyDoc.webkitExitPointerLock;
if (document.exitPointerLock) {
document.exitPointerLock();
}
};
/**
* Ask the browser to promote the current element to fullscreen rendering mode
* @param element defines the DOM element to promote
*/
Engine._RequestFullscreen = function (element) {
var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
if (!requestFunction) {
return;
}
requestFunction.call(element);
};
/**
* Asks the browser to exit fullscreen mode
*/
Engine._ExitFullscreen = function () {
var anyDoc = document;
if (document.exitFullscreen) {
document.exitFullscreen();
}
else if (anyDoc.mozCancelFullScreen) {
anyDoc.mozCancelFullScreen();
}
else if (anyDoc.webkitCancelFullScreen) {
anyDoc.webkitCancelFullScreen();
}
else if (anyDoc.msCancelFullScreen) {
anyDoc.msCancelFullScreen();
}
};
// Const statics
/** Defines that alpha blending is disabled */
Engine.ALPHA_DISABLE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_DISABLE;
/** Defines that alpha blending to SRC ALPHA * SRC + DEST */
Engine.ALPHA_ADD = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_ADD;
/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
Engine.ALPHA_COMBINE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_COMBINE;
/** Defines that alpha blending to DEST - SRC * DEST */
Engine.ALPHA_SUBTRACT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_SUBTRACT;
/** Defines that alpha blending to SRC * DEST */
Engine.ALPHA_MULTIPLY = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_MULTIPLY;
/** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
Engine.ALPHA_MAXIMIZED = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_MAXIMIZED;
/** Defines that alpha blending to SRC + DEST */
Engine.ALPHA_ONEONE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_ONEONE;
/** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
Engine.ALPHA_PREMULTIPLIED = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_PREMULTIPLIED;
/**
* Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
* Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
*/
Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF;
/** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
Engine.ALPHA_INTERPOLATE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_INTERPOLATE;
/**
* Defines that alpha blending to SRC + (1 - SRC) * DEST
* Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
*/
Engine.ALPHA_SCREENMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALPHA_SCREENMODE;
/** Defines that the ressource is not delayed*/
Engine.DELAYLOADSTATE_NONE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NONE;
/** Defines that the ressource was successfully delay loaded */
Engine.DELAYLOADSTATE_LOADED = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_LOADED;
/** Defines that the ressource is currently delay loading */
Engine.DELAYLOADSTATE_LOADING = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_LOADING;
/** Defines that the ressource is delayed and has not started loading */
Engine.DELAYLOADSTATE_NOTLOADED = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DELAYLOADSTATE_NOTLOADED;
// Depht or Stencil test Constants.
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
Engine.NEVER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].NEVER;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn */
Engine.ALWAYS = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].ALWAYS;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
Engine.LESS = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].LESS;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
Engine.EQUAL = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].EQUAL;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value */
Engine.LEQUAL = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].LEQUAL;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
Engine.GREATER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].GREATER;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value */
Engine.GEQUAL = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].GEQUAL;
/** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value */
Engine.NOTEQUAL = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].NOTEQUAL;
// Stencil Actions Constants.
/** Passed to stencilOperation to specify that stencil value must be kept */
Engine.KEEP = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].KEEP;
/** Passed to stencilOperation to specify that stencil value must be replaced */
Engine.REPLACE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].REPLACE;
/** Passed to stencilOperation to specify that stencil value must be incremented */
Engine.INCR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].INCR;
/** Passed to stencilOperation to specify that stencil value must be decremented */
Engine.DECR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DECR;
/** Passed to stencilOperation to specify that stencil value must be inverted */
Engine.INVERT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].INVERT;
/** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
Engine.INCR_WRAP = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].INCR_WRAP;
/** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
Engine.DECR_WRAP = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].DECR_WRAP;
/** Texture is not repeating outside of 0..1 UVs */
Engine.TEXTURE_CLAMP_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CLAMP_ADDRESSMODE;
/** Texture is repeating outside of 0..1 UVs */
Engine.TEXTURE_WRAP_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_WRAP_ADDRESSMODE;
/** Texture is repeating and mirrored */
Engine.TEXTURE_MIRROR_ADDRESSMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_MIRROR_ADDRESSMODE;
/** ALPHA */
Engine.TEXTUREFORMAT_ALPHA = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_ALPHA;
/** LUMINANCE */
Engine.TEXTUREFORMAT_LUMINANCE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_LUMINANCE;
/** LUMINANCE_ALPHA */
Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA;
/** RGB */
Engine.TEXTUREFORMAT_RGB = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGB;
/** RGBA */
Engine.TEXTUREFORMAT_RGBA = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA;
/** RED */
Engine.TEXTUREFORMAT_RED = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RED;
/** RED (2nd reference) */
Engine.TEXTUREFORMAT_R = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_R;
/** RG */
Engine.TEXTUREFORMAT_RG = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RG;
/** RED_INTEGER */
Engine.TEXTUREFORMAT_RED_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RED_INTEGER;
/** RED_INTEGER (2nd reference) */
Engine.TEXTUREFORMAT_R_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_R_INTEGER;
/** RG_INTEGER */
Engine.TEXTUREFORMAT_RG_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RG_INTEGER;
/** RGB_INTEGER */
Engine.TEXTUREFORMAT_RGB_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGB_INTEGER;
/** RGBA_INTEGER */
Engine.TEXTUREFORMAT_RGBA_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTUREFORMAT_RGBA_INTEGER;
/** UNSIGNED_BYTE */
Engine.TEXTURETYPE_UNSIGNED_BYTE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_BYTE;
/** UNSIGNED_BYTE (2nd reference) */
Engine.TEXTURETYPE_UNSIGNED_INT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INT;
/** FLOAT */
Engine.TEXTURETYPE_FLOAT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_FLOAT;
/** HALF_FLOAT */
Engine.TEXTURETYPE_HALF_FLOAT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_HALF_FLOAT;
/** BYTE */
Engine.TEXTURETYPE_BYTE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_BYTE;
/** SHORT */
Engine.TEXTURETYPE_SHORT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_SHORT;
/** UNSIGNED_SHORT */
Engine.TEXTURETYPE_UNSIGNED_SHORT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_SHORT;
/** INT */
Engine.TEXTURETYPE_INT = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_INT;
/** UNSIGNED_INT */
Engine.TEXTURETYPE_UNSIGNED_INTEGER = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INTEGER;
/** UNSIGNED_SHORT_4_4_4_4 */
Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4;
/** UNSIGNED_SHORT_5_5_5_1 */
Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1;
/** UNSIGNED_SHORT_5_6_5 */
Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_6_5;
/** UNSIGNED_INT_2_10_10_10_REV */
Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV;
/** UNSIGNED_INT_24_8 */
Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INT_24_8;
/** UNSIGNED_INT_10F_11F_11F_REV */
Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV;
/** UNSIGNED_INT_5_9_9_9_REV */
Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV;
/** FLOAT_32_UNSIGNED_INT_24_8_REV */
Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV;
/** nearest is mag = nearest and min = nearest and mip = linear */
Engine.TEXTURE_NEAREST_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
/** Bilinear is mag = linear and min = linear and mip = nearest */
Engine.TEXTURE_BILINEAR_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE;
/** Trilinear is mag = linear and min = linear and mip = linear */
Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE;
/** nearest is mag = nearest and min = nearest and mip = linear */
Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR;
/** Bilinear is mag = linear and min = linear and mip = nearest */
Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST;
/** Trilinear is mag = linear and min = linear and mip = linear */
Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR;
/** mag = nearest and min = nearest and mip = nearest */
Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST;
/** mag = nearest and min = linear and mip = nearest */
Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST;
/** mag = nearest and min = linear and mip = linear */
Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR;
/** mag = nearest and min = linear and mip = none */
Engine.TEXTURE_NEAREST_LINEAR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_LINEAR;
/** mag = nearest and min = nearest and mip = none */
Engine.TEXTURE_NEAREST_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_NEAREST_NEAREST;
/** mag = linear and min = nearest and mip = nearest */
Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST;
/** mag = linear and min = nearest and mip = linear */
Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR;
/** mag = linear and min = linear and mip = none */
Engine.TEXTURE_LINEAR_LINEAR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_LINEAR;
/** mag = linear and min = nearest and mip = none */
Engine.TEXTURE_LINEAR_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_LINEAR_NEAREST;
/** Explicit coordinates mode */
Engine.TEXTURE_EXPLICIT_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EXPLICIT_MODE;
/** Spherical coordinates mode */
Engine.TEXTURE_SPHERICAL_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SPHERICAL_MODE;
/** Planar coordinates mode */
Engine.TEXTURE_PLANAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PLANAR_MODE;
/** Cubic coordinates mode */
Engine.TEXTURE_CUBIC_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CUBIC_MODE;
/** Projection coordinates mode */
Engine.TEXTURE_PROJECTION_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PROJECTION_MODE;
/** Skybox coordinates mode */
Engine.TEXTURE_SKYBOX_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SKYBOX_MODE;
/** Inverse Cubic coordinates mode */
Engine.TEXTURE_INVCUBIC_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_INVCUBIC_MODE;
/** Equirectangular coordinates mode */
Engine.TEXTURE_EQUIRECTANGULAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EQUIRECTANGULAR_MODE;
/** Equirectangular Fixed coordinates mode */
Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
/** Equirectangular Fixed Mirrored coordinates mode */
Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
// Texture rescaling mode
/** Defines that texture rescaling will use a floor to find the closer power of 2 size */
Engine.SCALEMODE_FLOOR = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].SCALEMODE_FLOOR;
/** Defines that texture rescaling will look for the nearest power of 2 size */
Engine.SCALEMODE_NEAREST = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].SCALEMODE_NEAREST;
/** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
Engine.SCALEMODE_CEILING = _constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].SCALEMODE_CEILING;
/**
* Method called to create the default rescale post process on each engine.
*/
Engine._RescalePostProcessFactory = null;
return Engine;
}(_thinEngine__WEBPACK_IMPORTED_MODULE_5__["ThinEngine"]));
/***/ }),
/***/ "./Engines/engineCapabilities.ts":
/*!***************************************!*\
!*** ./Engines/engineCapabilities.ts ***!
\***************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Engines/engineStore.ts":
/*!********************************!*\
!*** ./Engines/engineStore.ts ***!
\********************************/
/*! exports provided: EngineStore */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return EngineStore; });
/**
* The engine store class is responsible to hold all the instances of Engine and Scene created
* during the life time of the application.
*/
var EngineStore = /** @class */ (function () {
function EngineStore() {
}
Object.defineProperty(EngineStore, "LastCreatedEngine", {
/**
* Gets the latest created engine
*/
get: function () {
if (this.Instances.length === 0) {
return null;
}
return this.Instances[this.Instances.length - 1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(EngineStore, "LastCreatedScene", {
/**
* Gets the latest created scene
*/
get: function () {
return this._LastCreatedScene;
},
enumerable: false,
configurable: true
});
/** Gets the list of created engines */
EngineStore.Instances = new Array();
/** @hidden */
EngineStore._LastCreatedScene = null;
/**
* Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
* @ignorenaming
*/
EngineStore.UseFallbackTexture = true;
/**
* Texture content used if a texture cannot loaded
* @ignorenaming
*/
EngineStore.FallbackTexture = "";
return EngineStore;
}());
/***/ }),
/***/ "./Engines/index.ts":
/*!**************************!*\
!*** ./Engines/index.ts ***!
\**************************/
/*! exports provided: Constants, ThinEngine, Engine, EngineStore, NullEngineOptions, NullEngine, _OcclusionDataStorage, _forceTransformFeedbackToBundle, EngineView, WebGLPipelineContext, WebGL2ShaderProcessor, NativeEngine, ShaderCodeInliner, PerformanceConfigurator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return _constants__WEBPACK_IMPORTED_MODULE_0__["Constants"]; });
/* harmony import */ var _engineCapabilities__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./engineCapabilities */ "./Engines/engineCapabilities.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _instancingAttributeInfo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./instancingAttributeInfo */ "./Engines/instancingAttributeInfo.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./thinEngine */ "./Engines/thinEngine.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThinEngine", function() { return _thinEngine__WEBPACK_IMPORTED_MODULE_3__["ThinEngine"]; });
/* harmony import */ var _engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./engine */ "./Engines/engine.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return _engine__WEBPACK_IMPORTED_MODULE_4__["Engine"]; });
/* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return _engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"]; });
/* harmony import */ var _nullEngine__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./nullEngine */ "./Engines/nullEngine.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return _nullEngine__WEBPACK_IMPORTED_MODULE_6__["NullEngineOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return _nullEngine__WEBPACK_IMPORTED_MODULE_6__["NullEngine"]; });
/* harmony import */ var _Extensions_index__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Extensions/index */ "./Engines/Extensions/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_7__["_OcclusionDataStorage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_7__["_forceTransformFeedbackToBundle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineView", function() { return _Extensions_index__WEBPACK_IMPORTED_MODULE_7__["EngineView"]; });
/* harmony import */ var _IPipelineContext__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./IPipelineContext */ "./Engines/IPipelineContext.ts");
/* empty/unused harmony star reexport *//* harmony import */ var _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./WebGL/webGLPipelineContext */ "./Engines/WebGL/webGLPipelineContext.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLPipelineContext", function() { return _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_9__["WebGLPipelineContext"]; });
/* harmony import */ var _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./WebGL/webGL2ShaderProcessors */ "./Engines/WebGL/webGL2ShaderProcessors.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGL2ShaderProcessor", function() { return _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_10__["WebGL2ShaderProcessor"]; });
/* harmony import */ var _nativeEngine__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./nativeEngine */ "./Engines/nativeEngine.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeEngine", function() { return _nativeEngine__WEBPACK_IMPORTED_MODULE_11__["NativeEngine"]; });
/* harmony import */ var _Processors_shaderCodeInliner__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Processors/shaderCodeInliner */ "./Engines/Processors/shaderCodeInliner.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeInliner", function() { return _Processors_shaderCodeInliner__WEBPACK_IMPORTED_MODULE_12__["ShaderCodeInliner"]; });
/* harmony import */ var _performanceConfigurator__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./performanceConfigurator */ "./Engines/performanceConfigurator.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerformanceConfigurator", function() { return _performanceConfigurator__WEBPACK_IMPORTED_MODULE_13__["PerformanceConfigurator"]; });
/***/ }),
/***/ "./Engines/instancingAttributeInfo.ts":
/*!********************************************!*\
!*** ./Engines/instancingAttributeInfo.ts ***!
\********************************************/
/*! no exports provided */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/***/ }),
/***/ "./Engines/nativeEngine.ts":
/*!*********************************!*\
!*** ./Engines/nativeEngine.ts ***!
\*********************************/
/*! exports provided: NativeEngine */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NativeEngine", function() { return NativeEngine; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/dataBuffer */ "./Meshes/dataBuffer.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts");
/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts");
/* harmony import */ var _thinEngine__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./thinEngine */ "./Engines/thinEngine.ts");
/* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Processors_shaderCodeInliner__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./Processors/shaderCodeInliner */ "./Engines/Processors/shaderCodeInliner.ts");
/* harmony import */ var _Engines_WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Engines/WebGL/webGL2ShaderProcessors */ "./Engines/WebGL/webGL2ShaderProcessors.ts");
var NativePipelineContext = /** @class */ (function () {
function NativePipelineContext() {
// TODO: async should be true?
this.isAsync = false;
this.isReady = false;
}
NativePipelineContext.prototype._getVertexShaderCode = function () {
return null;
};
NativePipelineContext.prototype._getFragmentShaderCode = function () {
return null;
};
// TODO: what should this do?
NativePipelineContext.prototype._handlesSpectorRebuildCallback = function (onCompiled) {
throw new Error("Not implemented");
};
return NativePipelineContext;
}());
/**
* Container for accessors for natively-stored mesh data buffers.
*/
var NativeDataBuffer = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NativeDataBuffer, _super);
function NativeDataBuffer() {
return _super !== null && _super.apply(this, arguments) || this;
}
return NativeDataBuffer;
}(_Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_4__["DataBuffer"]));
// TODO: change this to match bgfx.
// Must match Filter enum in SpectreEngine.h.
var NativeFilter = /** @class */ (function () {
function NativeFilter() {
}
NativeFilter.POINT = 0;
NativeFilter.MINPOINT_MAGPOINT_MIPPOINT = NativeFilter.POINT;
NativeFilter.BILINEAR = 1;
NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT = NativeFilter.BILINEAR;
NativeFilter.TRILINEAR = 2;
NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR = NativeFilter.TRILINEAR;
NativeFilter.ANISOTROPIC = 3;
NativeFilter.POINT_COMPARE = 4;
NativeFilter.TRILINEAR_COMPARE = 5;
NativeFilter.MINBILINEAR_MAGPOINT = 6;
NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR = NativeFilter.MINBILINEAR_MAGPOINT;
NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR = 7;
NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT = 8;
NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR = 9;
NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT = 10;
return NativeFilter;
}());
// these flags match bgfx.
var NativeClearFlags = /** @class */ (function () {
function NativeClearFlags() {
}
NativeClearFlags.CLEAR_COLOR = 1;
NativeClearFlags.CLEAR_DEPTH = 2;
NativeClearFlags.CLEAR_STENCIL = 4;
return NativeClearFlags;
}());
// TODO: change this to match bgfx.
// Must match AddressMode enum in SpectreEngine.h.
var NativeAddressMode = /** @class */ (function () {
function NativeAddressMode() {
}
NativeAddressMode.WRAP = 0;
NativeAddressMode.MIRROR = 1;
NativeAddressMode.CLAMP = 2;
NativeAddressMode.BORDER = 3;
NativeAddressMode.MIRROR_ONCE = 4;
return NativeAddressMode;
}());
var NativeTextureFormat = /** @class */ (function () {
function NativeTextureFormat() {
}
NativeTextureFormat.RGBA8 = 0;
NativeTextureFormat.RGBA32F = 1;
return NativeTextureFormat;
}());
/** @hidden */
var NativeTexture = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NativeTexture, _super);
function NativeTexture() {
return _super !== null && _super.apply(this, arguments) || this;
}
NativeTexture.prototype.getInternalTexture = function () {
return this;
};
NativeTexture.prototype.getViewCount = function () {
return 1;
};
return NativeTexture;
}(_Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"]));
/** @hidden */
var NativeEngine = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NativeEngine, _super);
function NativeEngine() {
var _this = _super.call(this, null) || this;
_this._native = new _native.Engine();
/** Defines the invalid handle returned by bgfx when resource creation goes wrong */
_this.INVALID_HANDLE = 65535;
_this._boundBuffersVertexArray = null;
_this._webGLVersion = 2;
_this.disableUniformBuffers = true;
// TODO: Initialize this more correctly based on the hardware capabilities.
// Init caps
_this._caps = {
maxTexturesImageUnits: 16,
maxVertexTextureImageUnits: 16,
maxCombinedTexturesImageUnits: 32,
maxTextureSize: 512,
maxCubemapTextureSize: 512,
maxRenderTextureSize: 512,
maxVertexAttribs: 16,
maxVaryingVectors: 16,
maxFragmentUniformVectors: 16,
maxVertexUniformVectors: 16,
standardDerivatives: true,
astc: null,
pvrtc: null,
etc1: null,
etc2: null,
maxAnisotropy: 16,
uintIndices: true,
fragmentDepthSupported: false,
highPrecisionShaderSupported: true,
colorBufferFloat: false,
textureFloat: false,
textureFloatLinearFiltering: false,
textureFloatRender: false,
textureHalfFloat: false,
textureHalfFloatLinearFiltering: false,
textureHalfFloatRender: false,
textureLOD: true,
drawBuffersExtension: false,
depthTextureExtension: false,
vertexArrayObject: true,
instancedArrays: false,
canUseTimestampForTimerQuery: false,
blendMinMax: false,
maxMSAASamples: 1
};
_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].Log("Babylon Native (v" + _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"].Version + ") launched");
// Wrappers
if (typeof URL === "undefined") {
window.URL = {
createObjectURL: function () { },
revokeObjectURL: function () { }
};
}
if (typeof Blob === "undefined") {
window.Blob = function () { };
}
// Shader processor
_this._shaderProcessor = new _Engines_WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_13__["WebGL2ShaderProcessor"]();
return _this;
}
NativeEngine.prototype.getHardwareScalingLevel = function () {
return 1.0;
};
NativeEngine.prototype.dispose = function () {
_super.prototype.dispose.call(this);
if (this._boundBuffersVertexArray) {
this._native.deleteVertexArray(this._boundBuffersVertexArray);
}
this._native.dispose();
};
/**
* Can be used to override the current requestAnimationFrame requester.
* @hidden
*/
NativeEngine.prototype._queueNewFrame = function (bindedRenderFunction, requester) {
// Use the provided requestAnimationFrame, unless the requester is the window. In that case, we will default to the Babylon Native version of requestAnimationFrame.
if (requester.requestAnimationFrame && requester !== window) {
requester.requestAnimationFrame(bindedRenderFunction);
}
else {
this._native.requestAnimationFrame(bindedRenderFunction);
}
return 0;
};
/**
* Override default engine behavior.
* @param color
* @param backBuffer
* @param depth
* @param stencil
*/
NativeEngine.prototype._bindUnboundFramebuffer = function (framebuffer) {
if (this._currentFramebuffer !== framebuffer) {
if (this._currentFramebuffer) {
this._native.unbindFramebuffer(this._currentFramebuffer);
}
if (framebuffer) {
this._native.bindFramebuffer(framebuffer);
}
this._currentFramebuffer = framebuffer;
}
};
/**
* Gets host document
* @returns the host document object
*/
NativeEngine.prototype.getHostDocument = function () {
return null;
};
NativeEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
if (stencil === void 0) { stencil = false; }
var mode = 0;
if (backBuffer && color) {
this._native.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
mode |= NativeClearFlags.CLEAR_COLOR;
}
if (depth) {
this._native.clearDepth(1.0);
mode |= NativeClearFlags.CLEAR_DEPTH;
}
if (stencil) {
this._native.clearStencil(0);
mode |= NativeClearFlags.CLEAR_STENCIL;
}
this._native.clear(mode);
};
NativeEngine.prototype.createIndexBuffer = function (indices, updateable) {
var data = this._normalizeIndexData(indices);
var buffer = new NativeDataBuffer();
buffer.references = 1;
buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
if (data.length) {
buffer.nativeIndexBuffer = this._native.createIndexBuffer(data, updateable !== null && updateable !== void 0 ? updateable : false);
if (buffer.nativeVertexBuffer === this.INVALID_HANDLE) {
throw new Error("Could not create a native index buffer.");
}
}
else {
buffer.nativeVertexBuffer = this.INVALID_HANDLE;
}
return buffer;
};
NativeEngine.prototype.createVertexBuffer = function (data, updateable) {
var buffer = new NativeDataBuffer();
buffer.references = 1;
buffer.nativeVertexBuffer = this._native.createVertexBuffer(ArrayBuffer.isView(data) ? data : new Float32Array(data), updateable !== null && updateable !== void 0 ? updateable : false);
if (buffer.nativeVertexBuffer === this.INVALID_HANDLE) {
throw new Error("Could not create a native vertex buffer.");
}
return buffer;
};
NativeEngine.prototype._recordVertexArrayObject = function (vertexArray, vertexBuffers, indexBuffer, effect) {
if (indexBuffer) {
this._native.recordIndexBuffer(vertexArray, indexBuffer.nativeIndexBuffer);
}
var attributes = effect.getAttributesNames();
for (var index = 0; index < attributes.length; index++) {
var location_1 = effect.getAttributeLocation(index);
if (location_1 >= 0) {
var kind = attributes[index];
var vertexBuffer = vertexBuffers[kind];
if (vertexBuffer) {
var buffer = vertexBuffer.getBuffer();
if (buffer) {
this._native.recordVertexBuffer(vertexArray, buffer.nativeVertexBuffer, location_1, vertexBuffer.byteOffset, vertexBuffer.byteStride, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized);
}
}
}
}
};
NativeEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
if (this._boundBuffersVertexArray) {
this._native.deleteVertexArray(this._boundBuffersVertexArray);
}
this._boundBuffersVertexArray = this._native.createVertexArray();
this._recordVertexArrayObject(this._boundBuffersVertexArray, vertexBuffers, indexBuffer, effect);
this._native.bindVertexArray(this._boundBuffersVertexArray);
};
NativeEngine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
var vertexArray = this._native.createVertexArray();
this._recordVertexArrayObject(vertexArray, vertexBuffers, indexBuffer, effect);
return vertexArray;
};
NativeEngine.prototype.bindVertexArrayObject = function (vertexArray) {
this._native.bindVertexArray(vertexArray);
};
NativeEngine.prototype.releaseVertexArrayObject = function (vertexArray) {
this._native.deleteVertexArray(vertexArray);
};
NativeEngine.prototype.getAttributes = function (pipelineContext, attributesNames) {
var nativePipelineContext = pipelineContext;
return this._native.getAttributes(nativePipelineContext.nativeProgram, attributesNames);
};
/**
* Draw a list of indexed primitives
* @param fillMode defines the primitive to use
* @param indexStart defines the starting index
* @param indexCount defines the number of index to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
NativeEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
// Apply states
this._drawCalls.addCount(1, false);
// TODO: Make this implementation more robust like core Engine version.
// Render
//var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
//var mult = this._uintIndicesCurrentlySet ? 4 : 2;
// if (instancesCount) {
// this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
// } else {
this._native.drawIndexed(fillMode, indexStart, indexCount);
// }
};
/**
* Draw a list of unindexed primitives
* @param fillMode defines the primitive to use
* @param verticesStart defines the index of first vertex to draw
* @param verticesCount defines the count of vertices to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
NativeEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
// Apply states
this._drawCalls.addCount(1, false);
// TODO: Make this implementation more robust like core Engine version.
// if (instancesCount) {
// this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
// } else {
this._native.draw(fillMode, verticesStart, verticesCount);
// }
};
NativeEngine.prototype.createPipelineContext = function () {
return new NativePipelineContext();
};
NativeEngine.prototype._preparePipelineContext = function (pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rebuildRebind, defines, transformFeedbackVaryings) {
var nativePipelineContext = pipelineContext;
if (createAsRaw) {
nativePipelineContext.nativeProgram = this.createRawShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
}
else {
nativePipelineContext.nativeProgram = this.createShaderProgram(pipelineContext, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
}
};
/** @hidden */
NativeEngine.prototype._isRenderingStateCompiled = function (pipelineContext) {
// TODO: support async shader compilcation
return true;
};
/** @hidden */
NativeEngine.prototype._executeWhenRenderingStateIsCompiled = function (pipelineContext, action) {
// TODO: support async shader compilcation
action();
};
NativeEngine.prototype.createRawShaderProgram = function (pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
throw new Error("Not Supported");
};
NativeEngine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
this.onBeforeShaderCompilationObservable.notifyObservers(this);
var vertexInliner = new _Processors_shaderCodeInliner__WEBPACK_IMPORTED_MODULE_12__["ShaderCodeInliner"](vertexCode);
vertexInliner.processCode();
vertexCode = vertexInliner.code;
var fragmentInliner = new _Processors_shaderCodeInliner__WEBPACK_IMPORTED_MODULE_12__["ShaderCodeInliner"](fragmentCode);
fragmentInliner.processCode();
fragmentCode = fragmentInliner.code;
vertexCode = _thinEngine__WEBPACK_IMPORTED_MODULE_10__["ThinEngine"]._ConcatenateShader(vertexCode, defines);
fragmentCode = _thinEngine__WEBPACK_IMPORTED_MODULE_10__["ThinEngine"]._ConcatenateShader(fragmentCode, defines);
var program = this._native.createProgram(vertexCode, fragmentCode);
this.onAfterShaderCompilationObservable.notifyObservers(this);
return program;
};
NativeEngine.prototype._setProgram = function (program) {
if (this._currentProgram !== program) {
this._native.setProgram(program);
this._currentProgram = program;
}
};
NativeEngine.prototype._releaseEffect = function (effect) {
// TODO
};
NativeEngine.prototype._deletePipelineContext = function (pipelineContext) {
// TODO
};
NativeEngine.prototype.getUniforms = function (pipelineContext, uniformsNames) {
var nativePipelineContext = pipelineContext;
return this._native.getUniforms(nativePipelineContext.nativeProgram, uniformsNames);
};
NativeEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) {
// TODO
throw new Error("Not Implemented");
};
NativeEngine.prototype.bindSamplers = function (effect) {
var nativePipelineContext = effect.getPipelineContext();
this._setProgram(nativePipelineContext.nativeProgram);
// TODO: share this with engine?
var samplers = effect.getSamplers();
for (var index = 0; index < samplers.length; index++) {
var uniform = effect.getUniform(samplers[index]);
if (uniform) {
this._boundUniforms[index] = uniform;
}
}
this._currentEffect = null;
};
NativeEngine.prototype.setMatrix = function (uniform, matrix) {
if (!uniform) {
return;
}
this._native.setMatrix(uniform, matrix.toArray());
};
NativeEngine.prototype.getRenderWidth = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._native.getRenderWidth();
};
NativeEngine.prototype.getRenderHeight = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._native.getRenderHeight();
};
NativeEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
this._cachedViewport = viewport;
this._native.setViewPort(viewport.x, viewport.y, viewport.width, viewport.height);
};
NativeEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
if (zOffset === void 0) { zOffset = 0; }
if (reverseSide === void 0) { reverseSide = false; }
this._native.setState(culling, zOffset, reverseSide);
};
/**
* Set the z offset to apply to current rendering
* @param value defines the offset to apply
*/
NativeEngine.prototype.setZOffset = function (value) {
this._native.setZOffset(value);
};
/**
* Gets the current value of the zOffset
* @returns the current zOffset state
*/
NativeEngine.prototype.getZOffset = function () {
return this._native.getZOffset();
};
/**
* Enable or disable depth buffering
* @param enable defines the state to set
*/
NativeEngine.prototype.setDepthBuffer = function (enable) {
this._native.setDepthTest(enable);
};
/**
* Gets a boolean indicating if depth writing is enabled
* @returns the current depth writing state
*/
NativeEngine.prototype.getDepthWrite = function () {
return this._native.getDepthWrite();
};
/**
* Enable or disable depth writing
* @param enable defines the state to set
*/
NativeEngine.prototype.setDepthWrite = function (enable) {
this._native.setDepthWrite(enable);
};
/**
* Enable or disable color writing
* @param enable defines the state to set
*/
NativeEngine.prototype.setColorWrite = function (enable) {
this._native.setColorWrite(enable);
this._colorWrite = enable;
};
/**
* Gets a boolean indicating if color writing is enabled
* @returns the current color writing state
*/
NativeEngine.prototype.getColorWrite = function () {
return this._colorWrite;
};
/**
* Sets alpha constants used by some alpha blending modes
* @param r defines the red component
* @param g defines the green component
* @param b defines the blue component
* @param a defines the alpha component
*/
NativeEngine.prototype.setAlphaConstants = function (r, g, b, a) {
throw new Error("Setting alpha blend constant color not yet implemented.");
};
/**
* Sets the current alpha mode
* @param mode defines the mode to use (one of the BABYLON.Constants.ALPHA_XXX)
* @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
* @see https://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
*/
NativeEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
if (this._alphaMode === mode) {
return;
}
this._native.setBlendMode(mode);
if (!noDepthWriteChange) {
this.setDepthWrite(mode === _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].ALPHA_DISABLE);
}
this._alphaMode = mode;
};
/**
* Gets the current alpha mode
* @see https://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
* @returns the current alpha mode
*/
NativeEngine.prototype.getAlphaMode = function () {
return this._alphaMode;
};
NativeEngine.prototype.setInt = function (uniform, int) {
if (!uniform) {
return;
}
this._native.setInt(uniform, int);
};
NativeEngine.prototype.setIntArray = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setIntArray(uniform, array);
};
NativeEngine.prototype.setIntArray2 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setIntArray2(uniform, array);
};
NativeEngine.prototype.setIntArray3 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setIntArray3(uniform, array);
};
NativeEngine.prototype.setIntArray4 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setIntArray4(uniform, array);
};
NativeEngine.prototype.setFloatArray = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray(uniform, array);
};
NativeEngine.prototype.setFloatArray2 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray2(uniform, array);
};
NativeEngine.prototype.setFloatArray3 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray3(uniform, array);
};
NativeEngine.prototype.setFloatArray4 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray4(uniform, array);
};
NativeEngine.prototype.setArray = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray(uniform, array);
};
NativeEngine.prototype.setArray2 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray2(uniform, array);
};
NativeEngine.prototype.setArray3 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray3(uniform, array);
};
NativeEngine.prototype.setArray4 = function (uniform, array) {
if (!uniform) {
return;
}
this._native.setFloatArray4(uniform, array);
};
NativeEngine.prototype.setMatrices = function (uniform, matrices) {
if (!uniform) {
return;
}
this._native.setMatrices(uniform, matrices);
};
NativeEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
if (!uniform) {
return;
}
this._native.setMatrix3x3(uniform, matrix);
};
NativeEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
if (!uniform) {
return;
}
this._native.setMatrix2x2(uniform, matrix);
};
NativeEngine.prototype.setFloat = function (uniform, value) {
if (!uniform) {
return;
}
this._native.setFloat(uniform, value);
};
NativeEngine.prototype.setFloat2 = function (uniform, x, y) {
if (!uniform) {
return;
}
this._native.setFloat2(uniform, x, y);
};
NativeEngine.prototype.setFloat3 = function (uniform, x, y, z) {
if (!uniform) {
return;
}
this._native.setFloat3(uniform, x, y, z);
};
NativeEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
if (!uniform) {
return;
}
this._native.setFloat4(uniform, x, y, z, w);
};
NativeEngine.prototype.setColor3 = function (uniform, color3) {
if (!uniform) {
return;
}
this._native.setFloat3(uniform, color3.r, color3.g, color3.b);
};
NativeEngine.prototype.setColor4 = function (uniform, color3, alpha) {
if (!uniform) {
return;
}
this._native.setFloat4(uniform, color3.r, color3.g, color3.b, alpha);
};
NativeEngine.prototype.wipeCaches = function (bruteForce) {
if (this.preventCacheWipeBetweenFrames) {
return;
}
this.resetTextureCache();
this._currentEffect = null;
if (bruteForce) {
this._currentProgram = null;
this._stencilState.reset();
this._depthCullingState.reset();
this._alphaState.reset();
}
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
};
NativeEngine.prototype._createTexture = function () {
return this._native.createTexture();
};
NativeEngine.prototype._deleteTexture = function (texture) {
this._native.deleteTexture(texture);
};
// TODO: Refactor to share more logic with babylon.engine.ts version.
/**
* Usually called from Texture.ts.
* Passed information to create a WebGLTexture
* @param url defines a value which contains one of the following:
* * A conventional http URL, e.g. 'http://...' or 'file://...'
* * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
* * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
* @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
* @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
* @param scene needed for loading to the correct scene
* @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
* @param onLoad optional callback to be called upon successful completion
* @param onError optional callback to be called upon failure
* @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
* @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
* @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
* @param forcedExtension defines the extension to use to pick the right loader
* @param mimeType defines an optional mime type
* @returns a InternalTexture for assignment back into BABYLON.Texture
*/
NativeEngine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension, mimeType) {
var _this = this;
if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (buffer === void 0) { buffer = null; }
if (fallback === void 0) { fallback = null; }
if (format === void 0) { format = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
url = url || "";
var fromData = url.substr(0, 5) === "data:";
//const fromBlob = url.substr(0, 5) === "blob:";
var isBase64 = fromData && url.indexOf(";base64,") !== -1;
var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTextureSource"].Url);
var originalUrl = url;
if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
url = this._transformTextureUrl(url);
}
// establish the file extension, if possible
var lastDot = url.lastIndexOf('.');
var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
var loader = null;
for (var _i = 0, _a = _Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders; _i < _a.length; _i++) {
var availableLoader = _a[_i];
if (availableLoader.canLoad(extension)) {
loader = availableLoader;
break;
}
}
if (scene) {
scene._addPendingData(texture);
}
texture.url = url;
texture.generateMipMaps = !noMipmap;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
if (!this.doNotHandleContextLost) {
// Keep a link to the buffer only if we plan to handle context lost
texture._buffer = buffer;
}
var onLoadObserver = null;
if (onLoad && !fallback) {
onLoadObserver = texture.onLoadedObservable.add(onLoad);
}
if (!fallback) {
this._internalTexturesCache.push(texture);
}
var onInternalError = function (message, exception) {
if (scene) {
scene._removePendingData(texture);
}
if (url === originalUrl) {
if (onLoadObserver) {
texture.onLoadedObservable.remove(onLoadObserver);
}
if (_engineStore__WEBPACK_IMPORTED_MODULE_11__["EngineStore"].UseFallbackTexture) {
_this.createTexture(_engineStore__WEBPACK_IMPORTED_MODULE_11__["EngineStore"].FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
}
if (onError) {
onError((message || "Unknown error") + (_engineStore__WEBPACK_IMPORTED_MODULE_11__["EngineStore"].UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
}
}
else {
// fall back to the original url if the transformed url fails to load
_Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("Failed to load " + url + ", falling back to " + originalUrl);
_this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType);
}
};
// processing for non-image formats
if (loader) {
throw new Error("Loading textures from IInternalTextureLoader not yet implemented.");
}
else {
var onload_1 = function (data) {
var webGLTexture = texture._webGLTexture;
if (!webGLTexture) {
if (scene) {
scene._removePendingData(texture);
}
return;
}
_this._native.loadTexture(webGLTexture, data, !noMipmap, invertY, function () {
texture.baseWidth = _this._native.getTextureWidth(webGLTexture);
texture.baseHeight = _this._native.getTextureHeight(webGLTexture);
texture.width = texture.baseWidth;
texture.height = texture.baseHeight;
texture.isReady = true;
var filter = _this._getSamplingFilter(samplingMode);
_this._native.setTextureSampling(webGLTexture, filter);
if (scene) {
scene._removePendingData(texture);
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
}, function () {
throw new Error("Could not load a native texture.");
});
};
if (fromData) {
if (buffer instanceof ArrayBuffer) {
onload_1(new Uint8Array(buffer));
}
else if (ArrayBuffer.isView(buffer)) {
onload_1(buffer);
}
else if (typeof buffer === "string") {
onload_1(new Uint8Array(_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].DecodeBase64(buffer)));
}
else {
throw new Error("Unsupported buffer type");
}
}
else {
if (isBase64) {
onload_1(new Uint8Array(_Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].DecodeBase64(url)));
}
else {
this._loadFile(url, function (data) { return onload_1(new Uint8Array(data)); }, undefined, undefined, true, function (request, exception) {
onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
});
}
}
}
return texture;
};
/**
* Creates a cube texture
* @param rootUrl defines the url where the files to load is located
* @param scene defines the current scene
* @param files defines the list of files to load (1 per face)
* @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
* @param onLoad defines an optional callback raised when the texture is loaded
* @param onError defines an optional callback raised if there is an issue to load the texture
* @param format defines the format of the data
* @param forcedExtension defines the extension to use to pick the right loader
* @param createPolynomials if a polynomial sphere should be created for the cube texture
* @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
* @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
* @param fallback defines texture to use while falling back when (compressed) texture file not found.
* @returns the cube texture as an InternalTexture
*/
NativeEngine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
var _this = this;
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
if (createPolynomials === void 0) { createPolynomials = false; }
if (lodScale === void 0) { lodScale = 0; }
if (lodOffset === void 0) { lodOffset = 0; }
if (fallback === void 0) { fallback = null; }
var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTextureSource"].Cube);
texture.isCube = true;
texture.url = rootUrl;
texture.generateMipMaps = !noMipmap;
texture._lodGenerationScale = lodScale;
texture._lodGenerationOffset = lodOffset;
if (!this._doNotHandleContextLost) {
texture._extension = forcedExtension;
texture._files = files;
}
var lastDot = rootUrl.lastIndexOf('.');
var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
// TODO: use texture loader to load env files?
if (extension === ".env") {
var onloaddata_1 = function (data) {
var info = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_6__["EnvironmentTextureTools"].GetEnvInfo(data);
texture.width = info.width;
texture.height = info.width;
_Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_6__["EnvironmentTextureTools"].UploadEnvSpherical(texture, info);
if (info.version !== 1) {
throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
}
var specularInfo = info.specular;
if (!specularInfo) {
throw new Error("Nothing else parsed so far");
}
texture._lodGenerationScale = specularInfo.lodGenerationScale;
var imageData = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_6__["EnvironmentTextureTools"].CreateImageDataArrayBufferViews(data, info);
texture.format = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTUREFORMAT_RGBA;
texture.type = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_UNSIGNED_INT;
texture.generateMipMaps = true;
texture.getEngine().updateTextureSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].TRILINEAR_SAMPLINGMODE, texture);
texture._isRGBD = true;
texture.invertY = true;
_this._native.loadCubeTextureWithMips(texture._webGLTexture, imageData, function () {
texture.isReady = true;
if (onLoad) {
onLoad();
}
}, function () {
throw new Error("Could not load a native cube texture.");
});
};
if (files && files.length === 6) {
throw new Error("Multi-file loading not allowed on env files.");
}
else {
var onInternalError = function (request, exception) {
if (onError && request) {
onError(request.status + " " + request.statusText, exception);
}
};
this._loadFile(rootUrl, function (data) { return onloaddata_1(new Uint8Array(data)); }, undefined, undefined, true, onInternalError);
}
}
else {
if (!files || files.length !== 6) {
throw new Error("Cannot load cubemap because 6 files were not defined");
}
// Reorder from [+X, +Y, +Z, -X, -Y, -Z] to [+X, -X, +Y, -Y, +Z, -Z].
var reorderedFiles = [files[0], files[3], files[1], files[4], files[2], files[5]];
Promise.all(reorderedFiles.map(function (file) { return _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].LoadFileAsync(file).then(function (data) { return new Uint8Array(data); }); })).then(function (data) {
return new Promise(function (resolve, reject) {
_this._native.loadCubeTexture(texture._webGLTexture, data, !noMipmap, resolve, reject);
});
}).then(function () {
texture.isReady = true;
if (onLoad) {
onLoad();
}
}, function (error) {
if (onError) {
onError("Failed to load cubemap: " + error.message, error);
}
});
}
this._internalTexturesCache.push(texture);
return texture;
};
// Returns a NativeFilter.XXXX value.
NativeEngine.prototype._getSamplingFilter = function (samplingMode) {
switch (samplingMode) {
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE:
return NativeFilter.MINLINEAR_MAGLINEAR_MIPPOINT;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE:
return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE:
return NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST:
return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST:
return NativeFilter.MINLINEAR_MAGPOINT_MIPPOINT;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR:
return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_LINEAR:
return NativeFilter.MINLINEAR_MAGPOINT_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_NEAREST:
return NativeFilter.MINPOINT_MAGPOINT_MIPPOINT;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST:
return NativeFilter.MINPOINT_MAGLINEAR_MIPPOINT;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR:
return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_LINEAR_LINEAR:
return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_LINEAR_NEAREST:
return NativeFilter.MINPOINT_MAGLINEAR_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR:
return NativeFilter.MINPOINT_MAGPOINT_MIPLINEAR;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST:
return NativeFilter.MINLINEAR_MAGLINEAR_MIPLINEAR;
default:
throw new Error("Unexpected sampling mode: " + samplingMode + ".");
}
};
NativeEngine._GetNativeTextureFormat = function (format, type) {
if (format == _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTUREFORMAT_RGBA && type == _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_UNSIGNED_INT) {
return NativeTextureFormat.RGBA8;
}
else if (format == _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTUREFORMAT_RGBA && type == _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_FLOAT) {
return NativeTextureFormat.RGBA32F;
}
else {
throw new Error("Unexpected texture format or type: format " + format + ", type " + type + ".");
}
};
NativeEngine.prototype.createRenderTargetTexture = function (size, options) {
var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_7__["RenderTargetCreationOptions"]();
if (options !== undefined && typeof options === "object") {
fullOptions.generateMipMaps = options.generateMipMaps;
fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
fullOptions.type = options.type === undefined ? _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_UNSIGNED_INT : options.type;
fullOptions.samplingMode = options.samplingMode === undefined ? _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
fullOptions.format = options.format === undefined ? _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTUREFORMAT_RGBA : options.format;
}
else {
fullOptions.generateMipMaps = options;
fullOptions.generateDepthBuffer = true;
fullOptions.generateStencilBuffer = false;
fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_UNSIGNED_INT;
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE;
fullOptions.format = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTUREFORMAT_RGBA;
}
if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
// if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
else if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
// if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
}
var texture = new NativeTexture(this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTextureSource"].RenderTarget);
var width = size.width || size;
var height = size.height || size;
if (fullOptions.type === _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURETYPE_UNSIGNED_INT;
_Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
}
var framebuffer = this._native.createFramebuffer(texture._webGLTexture, width, height, NativeEngine._GetNativeTextureFormat(fullOptions.format, fullOptions.type), fullOptions.samplingMode, fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, fullOptions.generateMipMaps ? true : false);
texture._framebuffer = framebuffer;
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture.format = fullOptions.format;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
this._internalTexturesCache.push(texture);
return texture;
};
NativeEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
if (texture._webGLTexture) {
var filter = this._getSamplingFilter(samplingMode);
this._native.setTextureSampling(texture._webGLTexture, filter);
}
texture.samplingMode = samplingMode;
};
NativeEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
if (faceIndex) {
throw new Error("Cuboid frame buffers are not yet supported in NativeEngine.");
}
if (requiredWidth || requiredHeight) {
throw new Error("Required width/height for frame buffers not yet supported in NativeEngine.");
}
if (forceFullscreenViewport) {
throw new Error("forceFullscreenViewport for frame buffers not yet supported in NativeEngine.");
}
this._bindUnboundFramebuffer(texture._framebuffer);
};
NativeEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
if (disableGenerateMipMaps) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_8__["Logger"].Warn("Disabling mipmap generation not yet supported in NativeEngine. Ignoring.");
}
if (onBeforeUnbind) {
onBeforeUnbind();
}
this._bindUnboundFramebuffer(null);
};
NativeEngine.prototype.createDynamicVertexBuffer = function (data) {
return this.createVertexBuffer(data, true);
};
NativeEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
if (offset === void 0) { offset = 0; }
var buffer = indexBuffer;
var data = this._normalizeIndexData(indices);
buffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
this._native.updateDynamicIndexBuffer(buffer.nativeIndexBuffer, data, offset);
};
/**
* Updates a dynamic vertex buffer.
* @param vertexBuffer the vertex buffer to update
* @param data the data used to update the vertex buffer
* @param byteOffset the byte offset of the data (optional)
* @param byteLength the byte length of the data (optional)
*/
NativeEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
var buffer = vertexBuffer;
var dataView = ArrayBuffer.isView(data) ? data : new Float32Array(data);
this._native.updateDynamicVertexBuffer(buffer.nativeVertexBuffer, dataView, byteOffset !== null && byteOffset !== void 0 ? byteOffset : 0, byteLength !== null && byteLength !== void 0 ? byteLength : dataView.byteLength);
};
// TODO: Refactor to share more logic with base Engine implementation.
NativeEngine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
if (depthStencilTexture === void 0) { depthStencilTexture = false; }
var uniform = this._boundUniforms[channel];
if (!uniform) {
return false;
}
// Not ready?
if (!texture) {
if (this._boundTexturesCache[channel] != null) {
this._activeChannel = channel;
this._native.setTexture(uniform, null);
}
return false;
}
// Video
if (texture.video) {
this._activeChannel = channel;
texture.update();
}
else if (texture.delayLoadState === _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].DELAYLOADSTATE_NOTLOADED) { // Delay loading
texture.delayLoad();
return false;
}
var internalTexture;
if (depthStencilTexture) {
internalTexture = texture.depthStencilTexture;
}
else if (texture.isReady()) {
internalTexture = texture.getInternalTexture();
}
else if (texture.isCube) {
internalTexture = this.emptyCubeTexture;
}
else if (texture.is3D) {
internalTexture = this.emptyTexture3D;
}
else if (texture.is2DArray) {
internalTexture = this.emptyTexture2DArray;
}
else {
internalTexture = this.emptyTexture;
}
this._activeChannel = channel;
if (!internalTexture ||
!internalTexture._webGLTexture) {
return false;
}
this._native.setTextureWrapMode(internalTexture._webGLTexture, this._getAddressMode(texture.wrapU), this._getAddressMode(texture.wrapV), this._getAddressMode(texture.wrapR));
this._updateAnisotropicLevel(texture);
this._native.setTexture(uniform, internalTexture._webGLTexture);
return true;
};
// TODO: Share more of this logic with the base implementation.
// TODO: Rename to match naming in base implementation once refactoring allows different parameters.
NativeEngine.prototype._updateAnisotropicLevel = function (texture) {
var internalTexture = texture.getInternalTexture();
var value = texture.anisotropicFilteringLevel;
if (!internalTexture || !internalTexture._webGLTexture) {
return;
}
if (internalTexture._cachedAnisotropicFilteringLevel !== value) {
this._native.setTextureAnisotropicLevel(internalTexture._webGLTexture, value);
internalTexture._cachedAnisotropicFilteringLevel = value;
}
};
// Returns a NativeAddressMode.XXX value.
NativeEngine.prototype._getAddressMode = function (wrapMode) {
switch (wrapMode) {
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_WRAP_ADDRESSMODE:
return NativeAddressMode.WRAP;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_CLAMP_ADDRESSMODE:
return NativeAddressMode.CLAMP;
case _constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].TEXTURE_MIRROR_ADDRESSMODE:
return NativeAddressMode.MIRROR;
default:
throw new Error("Unexpected wrap mode: " + wrapMode + ".");
}
};
/** @hidden */
NativeEngine.prototype._bindTexture = function (channel, texture) {
throw new Error("_bindTexture not implemented.");
};
NativeEngine.prototype._deleteBuffer = function (buffer) {
if (buffer.nativeIndexBuffer) {
this._native.deleteIndexBuffer(buffer.nativeIndexBuffer);
delete buffer.nativeIndexBuffer;
}
if (buffer.nativeVertexBuffer) {
this._native.deleteVertexBuffer(buffer.nativeVertexBuffer);
delete buffer.nativeVertexBuffer;
}
};
NativeEngine.prototype.releaseEffects = function () {
// TODO
};
/** @hidden */
NativeEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
throw new Error("_uploadCompressedDataToTextureDirectly not implemented.");
};
/** @hidden */
NativeEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
throw new Error("_uploadDataToTextureDirectly not implemented.");
};
/** @hidden */
NativeEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
throw new Error("_uploadArrayBufferViewToTexture not implemented.");
};
/** @hidden */
NativeEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
throw new Error("_uploadArrayBufferViewToTexture not implemented.");
};
return NativeEngine;
}(_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]));
/***/ }),
/***/ "./Engines/nullEngine.ts":
/*!*******************************!*\
!*** ./Engines/nullEngine.ts ***!
\*******************************/
/*! exports provided: NullEngineOptions, NullEngine */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return NullEngineOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return NullEngine; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/renderTargetCreationOptions */ "./Materials/Textures/renderTargetCreationOptions.ts");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts");
/* harmony import */ var _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/dataBuffer */ "./Meshes/dataBuffer.ts");
/* harmony import */ var _performanceConfigurator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./performanceConfigurator */ "./Engines/performanceConfigurator.ts");
/**
* Options to create the null engine
*/
var NullEngineOptions = /** @class */ (function () {
function NullEngineOptions() {
/**
* Render width (Default: 512)
*/
this.renderWidth = 512;
/**
* Render height (Default: 256)
*/
this.renderHeight = 256;
/**
* Texture size (Default: 512)
*/
this.textureSize = 512;
/**
* If delta time between frames should be constant
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
*/
this.deterministicLockstep = false;
/**
* Maximum about of steps between frames (Default: 4)
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
*/
this.lockstepMaxSteps = 4;
}
return NullEngineOptions;
}());
/**
* The null engine class provides support for headless version of babylon.js.
* This can be used in server side scenario or for testing purposes
*/
var NullEngine = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NullEngine, _super);
function NullEngine(options) {
if (options === void 0) { options = new NullEngineOptions(); }
var _this = _super.call(this, null) || this;
_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Instances.push(_this);
if (options.deterministicLockstep === undefined) {
options.deterministicLockstep = false;
}
if (options.lockstepMaxSteps === undefined) {
options.lockstepMaxSteps = 4;
}
_this._options = options;
_performanceConfigurator__WEBPACK_IMPORTED_MODULE_7__["PerformanceConfigurator"].SetMatrixPrecision(!!options.useHighPrecisionMatrix);
// Init caps
// We consider we are on a webgl1 capable device
_this._caps = {
maxTexturesImageUnits: 16,
maxVertexTextureImageUnits: 16,
maxCombinedTexturesImageUnits: 32,
maxTextureSize: 512,
maxCubemapTextureSize: 512,
maxRenderTextureSize: 512,
maxVertexAttribs: 16,
maxVaryingVectors: 16,
maxFragmentUniformVectors: 16,
maxVertexUniformVectors: 16,
standardDerivatives: false,
astc: null,
pvrtc: null,
etc1: null,
etc2: null,
maxAnisotropy: 0,
uintIndices: false,
fragmentDepthSupported: false,
highPrecisionShaderSupported: true,
colorBufferFloat: false,
textureFloat: false,
textureFloatLinearFiltering: false,
textureFloatRender: false,
textureHalfFloat: false,
textureHalfFloatLinearFiltering: false,
textureHalfFloatRender: false,
textureLOD: false,
drawBuffersExtension: false,
depthTextureExtension: false,
vertexArrayObject: false,
instancedArrays: false,
canUseTimestampForTimerQuery: false,
maxMSAASamples: 1,
blendMinMax: false
};
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log("Babylon.js v" + _Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"].Version + " - Null engine");
// Wrappers
var theCurrentGlobal = (typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : window);
if (typeof URL === "undefined") {
theCurrentGlobal.URL = {
createObjectURL: function () { },
revokeObjectURL: function () { }
};
}
if (typeof Blob === "undefined") {
theCurrentGlobal.Blob = function () { };
}
return _this;
}
/**
* Gets a boolean indicating that the engine is running in deterministic lock step mode
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
* @returns true if engine is in deterministic lock step mode
*/
NullEngine.prototype.isDeterministicLockStep = function () {
return this._options.deterministicLockstep;
};
/**
* Gets the max steps when engine is running in deterministic lock step
* @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
* @returns the max steps
*/
NullEngine.prototype.getLockstepMaxSteps = function () {
return this._options.lockstepMaxSteps;
};
/**
* Gets the current hardware scaling level.
* By default the hardware scaling level is computed from the window device ratio.
* if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
* @returns a number indicating the current hardware scaling level
*/
NullEngine.prototype.getHardwareScalingLevel = function () {
return 1.0;
};
/**
* Creates a vertex buffer
* @param vertices the data for the vertex buffer
* @returns the new WebGL static buffer
*/
NullEngine.prototype.createVertexBuffer = function (vertices) {
var buffer = new _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__["DataBuffer"]();
buffer.references = 1;
return buffer;
};
/**
* Creates a new index buffer
* @param indices defines the content of the index buffer
* @param updatable defines if the index buffer must be updatable
* @returns a new webGL buffer
*/
NullEngine.prototype.createIndexBuffer = function (indices) {
var buffer = new _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__["DataBuffer"]();
buffer.references = 1;
return buffer;
};
/**
* Clear the current render buffer or the current render target (if any is set up)
* @param color defines the color to use
* @param backBuffer defines if the back buffer must be cleared
* @param depth defines if the depth buffer must be cleared
* @param stencil defines if the stencil buffer must be cleared
*/
NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
if (stencil === void 0) { stencil = false; }
};
/**
* Gets the current render width
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the current render width
*/
NullEngine.prototype.getRenderWidth = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._options.renderWidth;
};
/**
* Gets the current render height
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the current render height
*/
NullEngine.prototype.getRenderHeight = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._options.renderHeight;
};
/**
* Set the WebGL's viewport
* @param viewport defines the viewport element to be used
* @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
* @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
*/
NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
this._cachedViewport = viewport;
};
NullEngine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context) {
return {
__SPECTOR_rebuildProgram: null,
};
};
/**
* Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
* @param pipelineContext defines the pipeline context to use
* @param uniformsNames defines the list of uniform names
* @returns an array of webGL uniform locations
*/
NullEngine.prototype.getUniforms = function (pipelineContext, uniformsNames) {
return [];
};
/**
* Gets the lsit of active attributes for a given webGL program
* @param pipelineContext defines the pipeline context to use
* @param attributesNames defines the list of attribute names to get
* @returns an array of indices indicating the offset of each attribute
*/
NullEngine.prototype.getAttributes = function (pipelineContext, attributesNames) {
return [];
};
/**
* Binds an effect to the webGL context
* @param effect defines the effect to bind
*/
NullEngine.prototype.bindSamplers = function (effect) {
this._currentEffect = null;
};
/**
* Activates an effect, mkaing it the current one (ie. the one used for rendering)
* @param effect defines the effect to activate
*/
NullEngine.prototype.enableEffect = function (effect) {
this._currentEffect = effect;
if (effect.onBind) {
effect.onBind(effect);
}
if (effect._onBindObservable) {
effect._onBindObservable.notifyObservers(effect);
}
};
/**
* Set various states to the webGL context
* @param culling defines backface culling state
* @param zOffset defines the value to apply to zOffset (0 by default)
* @param force defines if states must be applied even if cache is up to date
* @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
*/
NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
if (zOffset === void 0) { zOffset = 0; }
if (reverseSide === void 0) { reverseSide = false; }
};
/**
* Set the value of an uniform to an array of int32
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
NullEngine.prototype.setIntArray = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of int32 (stored as vec2)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
NullEngine.prototype.setIntArray2 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of int32 (stored as vec3)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
NullEngine.prototype.setIntArray3 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of int32 (stored as vec4)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
NullEngine.prototype.setIntArray4 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of float32
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of float32 to store
*/
NullEngine.prototype.setFloatArray = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of float32 (stored as vec2)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of float32 to store
*/
NullEngine.prototype.setFloatArray2 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of float32 (stored as vec3)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of float32 to store
*/
NullEngine.prototype.setFloatArray3 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of float32 (stored as vec4)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of float32 to store
*/
NullEngine.prototype.setFloatArray4 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of number
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
NullEngine.prototype.setArray = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of number (stored as vec2)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
NullEngine.prototype.setArray2 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of number (stored as vec3)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
NullEngine.prototype.setArray3 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of number (stored as vec4)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
NullEngine.prototype.setArray4 = function (uniform, array) {
};
/**
* Set the value of an uniform to an array of float32 (stored as matrices)
* @param uniform defines the webGL uniform location where to store the value
* @param matrices defines the array of float32 to store
*/
NullEngine.prototype.setMatrices = function (uniform, matrices) {
};
/**
* Set the value of an uniform to a matrix (3x3)
* @param uniform defines the webGL uniform location where to store the value
* @param matrix defines the Float32Array representing the 3x3 matrix to store
*/
NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
};
/**
* Set the value of an uniform to a matrix (2x2)
* @param uniform defines the webGL uniform location where to store the value
* @param matrix defines the Float32Array representing the 2x2 matrix to store
*/
NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
};
/**
* Set the value of an uniform to a number (float)
* @param uniform defines the webGL uniform location where to store the value
* @param value defines the float number to store
*/
NullEngine.prototype.setFloat = function (uniform, value) {
};
/**
* Set the value of an uniform to a vec2
* @param uniform defines the webGL uniform location where to store the value
* @param x defines the 1st component of the value
* @param y defines the 2nd component of the value
*/
NullEngine.prototype.setFloat2 = function (uniform, x, y) {
};
/**
* Set the value of an uniform to a vec3
* @param uniform defines the webGL uniform location where to store the value
* @param x defines the 1st component of the value
* @param y defines the 2nd component of the value
* @param z defines the 3rd component of the value
*/
NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
};
/**
* Set the value of an uniform to a boolean
* @param uniform defines the webGL uniform location where to store the value
* @param bool defines the boolean to store
*/
NullEngine.prototype.setBool = function (uniform, bool) {
};
/**
* Set the value of an uniform to a vec4
* @param uniform defines the webGL uniform location where to store the value
* @param x defines the 1st component of the value
* @param y defines the 2nd component of the value
* @param z defines the 3rd component of the value
* @param w defines the 4th component of the value
*/
NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
};
/**
* Sets the current alpha mode
* @param mode defines the mode to use (one of the Engine.ALPHA_XXX)
* @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
* @see https://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
*/
NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
if (this._alphaMode === mode) {
return;
}
this.alphaState.alphaBlend = (mode !== _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].ALPHA_DISABLE);
if (!noDepthWriteChange) {
this.setDepthWrite(mode === _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].ALPHA_DISABLE);
}
this._alphaMode = mode;
};
/**
* Bind webGl buffers directly to the webGL context
* @param vertexBuffers defines the vertex buffer to bind
* @param indexBuffer defines the index buffer to bind
* @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
* @param vertexStrideSize defines the vertex stride of the vertex buffer
* @param effect defines the effect associated with the vertex buffer
*/
NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
};
/**
* Force the entire cache to be cleared
* You should not have to use this function unless your engine needs to share the webGL context with another engine
* @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
*/
NullEngine.prototype.wipeCaches = function (bruteForce) {
if (this.preventCacheWipeBetweenFrames) {
return;
}
this.resetTextureCache();
this._currentEffect = null;
if (bruteForce) {
this._currentProgram = null;
this.stencilState.reset();
this.depthCullingState.reset();
this.alphaState.reset();
}
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
};
/**
* Send a draw order
* @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
* @param indexStart defines the starting index
* @param indexCount defines the number of index to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
};
/**
* Draw a list of indexed primitives
* @param fillMode defines the primitive to use
* @param indexStart defines the starting index
* @param indexCount defines the number of index to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
};
/**
* Draw a list of unindexed primitives
* @param fillMode defines the primitive to use
* @param verticesStart defines the index of first vertex to draw
* @param verticesCount defines the count of vertices to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
};
/** @hidden */
NullEngine.prototype._createTexture = function () {
return {};
};
/** @hidden */
NullEngine.prototype._releaseTexture = function (texture) {
};
/**
* Usually called from Texture.ts.
* Passed information to create a WebGLTexture
* @param urlArg defines a value which contains one of the following:
* * A conventional http URL, e.g. 'http://...' or 'file://...'
* * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
* * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
* @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
* @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
* @param scene needed for loading to the correct scene
* @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
* @param onLoad optional callback to be called upon successful completion
* @param onError optional callback to be called upon failure
* @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
* @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
* @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
* @param forcedExtension defines the extension to use to pick the right loader
* @param mimeType defines an optional mime type
* @returns a InternalTexture for assignment back into BABYLON.Texture
*/
NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension, mimeType) {
if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (buffer === void 0) { buffer = null; }
if (fallback === void 0) { fallback = null; }
if (format === void 0) { format = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTextureSource"].Url);
var url = String(urlArg);
texture.url = url;
texture.generateMipMaps = !noMipmap;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
texture.baseWidth = this._options.textureSize;
texture.baseHeight = this._options.textureSize;
texture.width = this._options.textureSize;
texture.height = this._options.textureSize;
if (format) {
texture.format = format;
}
texture.isReady = true;
if (onLoad) {
onLoad();
}
this._internalTexturesCache.push(texture);
return texture;
};
/**
* Creates a new render target texture
* @param size defines the size of the texture
* @param options defines the options used to create the texture
* @returns a new render target texture stored in an InternalTexture
*/
NullEngine.prototype.createRenderTargetTexture = function (size, options) {
var fullOptions = new _Materials_Textures_renderTargetCreationOptions__WEBPACK_IMPORTED_MODULE_3__["RenderTargetCreationOptions"]();
if (options !== undefined && typeof options === "object") {
fullOptions.generateMipMaps = options.generateMipMaps;
fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
fullOptions.type = options.type === undefined ? _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT : options.type;
fullOptions.samplingMode = options.samplingMode === undefined ? _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
}
else {
fullOptions.generateMipMaps = options;
fullOptions.generateDepthBuffer = true;
fullOptions.generateStencilBuffer = false;
fullOptions.type = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURETYPE_UNSIGNED_INT;
fullOptions.samplingMode = _constants__WEBPACK_IMPORTED_MODULE_5__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE;
}
var texture = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_4__["InternalTextureSource"].RenderTarget);
var width = size.width || size;
var height = size.height || size;
texture._depthStencilBuffer = {};
texture._framebuffer = {};
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = width;
texture.height = height;
texture.isReady = true;
texture.samples = 1;
texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
texture.samplingMode = fullOptions.samplingMode;
texture.type = fullOptions.type;
texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
this._internalTexturesCache.push(texture);
return texture;
};
/**
* Update the sampling mode of a given texture
* @param samplingMode defines the required sampling mode
* @param texture defines the texture to update
*/
NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
texture.samplingMode = samplingMode;
};
/**
* Binds the frame buffer to the specified texture.
* @param texture The texture to render to or null for the default canvas
* @param faceIndex The face of the texture to render to in case of cube texture
* @param requiredWidth The width of the target to render to
* @param requiredHeight The height of the target to render to
* @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
* @param lodLevel defines le lod level to bind to the frame buffer
*/
NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
this._currentRenderTarget = texture;
this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
if (this._cachedViewport && !forceFullscreenViewport) {
this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
}
};
/**
* Unbind the current render target texture from the webGL context
* @param texture defines the render target texture to unbind
* @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
* @param onBeforeUnbind defines a function which will be called before the effective unbind
*/
NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
this._currentRenderTarget = null;
if (onBeforeUnbind) {
if (texture._MSAAFramebuffer) {
this._currentFramebuffer = texture._framebuffer;
}
onBeforeUnbind();
}
this._currentFramebuffer = null;
};
/**
* Creates a dynamic vertex buffer
* @param vertices the data for the dynamic vertex buffer
* @returns the new WebGL dynamic buffer
*/
NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
var buffer = new _Meshes_dataBuffer__WEBPACK_IMPORTED_MODULE_6__["DataBuffer"]();
buffer.references = 1;
buffer.capacity = 1;
return buffer;
};
/**
* Update the content of a dynamic texture
* @param texture defines the texture to update
* @param canvas defines the canvas containing the source
* @param invertY defines if data must be stored with Y axis inverted
* @param premulAlpha defines if alpha is stored as premultiplied
* @param format defines the format of the data
* @param forceBindTexture if the texture should be forced to be bound eg. after a graphics context loss (Default: false)
*/
NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
if (premulAlpha === void 0) { premulAlpha = false; }
};
/**
* Gets a boolean indicating if all created effects are ready
* @returns true if all effects are ready
*/
NullEngine.prototype.areAllEffectsReady = function () {
return true;
};
/**
* @hidden
* Get the current error code of the webGL context
* @returns the error code
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
*/
NullEngine.prototype.getError = function () {
return 0;
};
/** @hidden */
NullEngine.prototype._getUnpackAlignement = function () {
return 1;
};
/** @hidden */
NullEngine.prototype._unpackFlipY = function (value) {
};
/**
* Update a dynamic index buffer
* @param indexBuffer defines the target index buffer
* @param indices defines the data to update
* @param offset defines the offset in the target index buffer where update should start
*/
NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
if (offset === void 0) { offset = 0; }
};
/**
* Updates a dynamic vertex buffer.
* @param vertexBuffer the vertex buffer to update
* @param vertices the data used to update the vertex buffer
* @param byteOffset the byte offset of the data (optional)
* @param byteLength the byte length of the data (optional)
*/
NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
};
/** @hidden */
NullEngine.prototype._bindTextureDirectly = function (target, texture) {
if (this._boundTexturesCache[this._activeChannel] !== texture) {
this._boundTexturesCache[this._activeChannel] = texture;
return true;
}
return false;
};
/** @hidden */
NullEngine.prototype._bindTexture = function (channel, texture) {
if (channel < 0) {
return;
}
this._bindTextureDirectly(0, texture);
};
NullEngine.prototype._deleteBuffer = function (buffer) {
};
/**
* Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
*/
NullEngine.prototype.releaseEffects = function () {
};
NullEngine.prototype.displayLoadingUI = function () {
};
NullEngine.prototype.hideLoadingUI = function () {
};
/** @hidden */
NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
};
/** @hidden */
NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
};
/** @hidden */
NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
};
/** @hidden */
NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
};
return NullEngine;
}(_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]));
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "./Engines/performanceConfigurator.ts":
/*!********************************************!*\
!*** ./Engines/performanceConfigurator.ts ***!
\********************************************/
/*! exports provided: PerformanceConfigurator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PerformanceConfigurator", function() { return PerformanceConfigurator; });
/** @hidden */
var PerformanceConfigurator = /** @class */ (function () {
function PerformanceConfigurator() {
}
/** @hidden */
PerformanceConfigurator.SetMatrixPrecision = function (use64bits) {
PerformanceConfigurator.MatrixTrackPrecisionChange = false;
if (use64bits && !PerformanceConfigurator.MatrixUse64Bits) {
if (PerformanceConfigurator.MatrixTrackedMatrices) {
for (var m = 0; m < PerformanceConfigurator.MatrixTrackedMatrices.length; ++m) {
var matrix = PerformanceConfigurator.MatrixTrackedMatrices[m];
var values = matrix._m;
matrix._m = new Array(16);
for (var i = 0; i < 16; ++i) {
matrix._m[i] = values[i];
}
}
}
}
PerformanceConfigurator.MatrixUse64Bits = use64bits;
PerformanceConfigurator.MatrixCurrentType = PerformanceConfigurator.MatrixUse64Bits ? Array : Float32Array;
PerformanceConfigurator.MatrixTrackedMatrices = null; // reclaim some memory, as we don't need _TrackedMatrices anymore
};
/** @hidden */
PerformanceConfigurator.MatrixUse64Bits = false;
/** @hidden */
PerformanceConfigurator.MatrixTrackPrecisionChange = true;
/** @hidden */
PerformanceConfigurator.MatrixCurrentType = Float32Array;
/** @hidden */
PerformanceConfigurator.MatrixTrackedMatrices = [];
return PerformanceConfigurator;
}());
/***/ }),
/***/ "./Engines/thinEngine.ts":
/*!*******************************!*\
!*** ./Engines/thinEngine.ts ***!
\*******************************/
/*! exports provided: ThinEngine */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ThinEngine", function() { return ThinEngine; });
/* harmony import */ var _engineStore__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Materials_effect__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/effect */ "./Materials/effect.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _States_depthCullingState__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../States/depthCullingState */ "./States/depthCullingState.ts");
/* harmony import */ var _States_stencilState__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../States/stencilState */ "./States/stencilState.ts");
/* harmony import */ var _States_alphaCullingState__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../States/alphaCullingState */ "./States/alphaCullingState.ts");
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./constants */ "./Engines/constants.ts");
/* harmony import */ var _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts");
/* harmony import */ var _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./WebGL/webGL2ShaderProcessors */ "./Engines/WebGL/webGL2ShaderProcessors.ts");
/* harmony import */ var _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Meshes/WebGL/webGLDataBuffer */ "./Meshes/WebGL/webGLDataBuffer.ts");
/* harmony import */ var _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./WebGL/webGLPipelineContext */ "./Engines/WebGL/webGLPipelineContext.ts");
/* harmony import */ var _Misc_canvasGenerator__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Misc/canvasGenerator */ "./Misc/canvasGenerator.ts");
/* harmony import */ var _performanceConfigurator__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./performanceConfigurator */ "./Engines/performanceConfigurator.ts");
/**
* Keeps track of all the buffer info used in engine.
*/
var BufferPointer = /** @class */ (function () {
function BufferPointer() {
}
return BufferPointer;
}());
/**
* The base engine class (root of all engines)
*/
var ThinEngine = /** @class */ (function () {
/**
* Creates a new engine
* @param canvasOrContext defines the canvas or WebGL context to use for rendering. If you provide a WebGL context, Babylon.js will not hook events on the canvas (like pointers, keyboards, etc...) so no event observables will be available. This is mostly used when Babylon.js is used as a plugin on a system which alreay used the WebGL context
* @param antialias defines enable antialiasing (default: false)
* @param options defines further options to be sent to the getContext() function
* @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
*/
function ThinEngine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
var _this = this;
if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
/**
* Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
*/
this.forcePOTTextures = false;
/**
* Gets a boolean indicating if the engine is currently rendering in fullscreen mode
*/
this.isFullscreen = false;
/**
* Gets or sets a boolean indicating if back faces must be culled (true by default)
*/
this.cullBackFaces = true;
/**
* Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
*/
this.renderEvenInBackground = true;
/**
* Gets or sets a boolean indicating that cache can be kept between frames
*/
this.preventCacheWipeBetweenFrames = false;
/** Gets or sets a boolean indicating if the engine should validate programs after compilation */
this.validateShaderPrograms = false;
/**
* Gets or sets a boolean indicating if depth buffer should be reverse, going from far to near.
* This can provide greater z depth for distant objects.
*/
this.useReverseDepthBuffer = false;
// Uniform buffers list
/**
* Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
*/
this.disableUniformBuffers = false;
/** @hidden */
this._uniformBuffers = new Array();
/** @hidden */
this._webGLVersion = 1.0;
this._windowIsBackground = false;
this._highPrecisionShadersAllowed = true;
/** @hidden */
this._badOS = false;
/** @hidden */
this._badDesktopOS = false;
this._renderingQueueLaunched = false;
this._activeRenderLoops = new Array();
// Lost context
/**
* Observable signaled when a context lost event is raised
*/
this.onContextLostObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* Observable signaled when a context restored event is raised
*/
this.onContextRestoredObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
this._contextWasLost = false;
/** @hidden */
this._doNotHandleContextLost = false;
/**
* Gets or sets a boolean indicating that vertex array object must be disabled even if they are supported
*/
this.disableVertexArrayObjects = false;
// States
/** @hidden */
this._colorWrite = true;
/** @hidden */
this._colorWriteChanged = true;
/** @hidden */
this._depthCullingState = new _States_depthCullingState__WEBPACK_IMPORTED_MODULE_4__["DepthCullingState"]();
/** @hidden */
this._stencilState = new _States_stencilState__WEBPACK_IMPORTED_MODULE_5__["StencilState"]();
/** @hidden */
this._alphaState = new _States_alphaCullingState__WEBPACK_IMPORTED_MODULE_6__["AlphaState"]();
/** @hidden */
this._alphaMode = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].ALPHA_ADD;
/** @hidden */
this._alphaEquation = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].ALPHA_DISABLE;
// Cache
/** @hidden */
this._internalTexturesCache = new Array();
/** @hidden */
this._activeChannel = 0;
this._currentTextureChannel = -1;
/** @hidden */
this._boundTexturesCache = {};
this._compiledEffects = {};
this._vertexAttribArraysEnabled = [];
this._uintIndicesCurrentlySet = false;
this._currentBoundBuffer = new Array();
/** @hidden */
this._currentFramebuffer = null;
/** @hidden */
this._dummyFramebuffer = null;
this._currentBufferPointers = new Array();
this._currentInstanceLocations = new Array();
this._currentInstanceBuffers = new Array();
this._vaoRecordInProgress = false;
this._mustWipeVertexAttributes = false;
this._nextFreeTextureSlots = new Array();
this._maxSimultaneousTextures = 0;
this._activeRequests = new Array();
/** @hidden */
this._transformTextureUrl = null;
/**
* Gets information about the current host
*/
this.hostInformation = {
isMobile: false
};
/**
* Defines whether the engine has been created with the premultipliedAlpha option on or not.
*/
this.premultipliedAlpha = true;
/**
* Observable event triggered before each texture is initialized
*/
this.onBeforeTextureInitObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
this._viewportCached = { x: 0, y: 0, z: 0, w: 0 };
this._unpackFlipYCached = null;
/**
* In case you are sharing the context with other applications, it might
* be interested to not cache the unpack flip y state to ensure a consistent
* value would be set.
*/
this.enableUnpackFlipYCached = true;
this._getDepthStencilBuffer = function (width, height, samples, internalFormat, msInternalFormat, attachment) {
var gl = _this._gl;
var depthStencilBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
if (samples > 1 && gl.renderbufferStorageMultisample) {
gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, msInternalFormat, width, height);
}
else {
gl.renderbufferStorage(gl.RENDERBUFFER, internalFormat, width, height);
}
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, depthStencilBuffer);
gl.bindRenderbuffer(gl.RENDERBUFFER, null);
return depthStencilBuffer;
};
this._boundUniforms = {};
var canvas = null;
if (!canvasOrContext) {
return;
}
options = options || {};
_performanceConfigurator__WEBPACK_IMPORTED_MODULE_15__["PerformanceConfigurator"].SetMatrixPrecision(!!options.useHighPrecisionMatrix);
if (canvasOrContext.getContext) {
canvas = canvasOrContext;
this._renderingCanvas = canvas;
if (antialias != null) {
options.antialias = antialias;
}
if (options.deterministicLockstep === undefined) {
options.deterministicLockstep = false;
}
if (options.lockstepMaxSteps === undefined) {
options.lockstepMaxSteps = 4;
}
if (options.timeStep === undefined) {
options.timeStep = 1 / 60;
}
if (options.preserveDrawingBuffer === undefined) {
options.preserveDrawingBuffer = false;
}
if (options.audioEngine === undefined) {
options.audioEngine = true;
}
if (options.stencil === undefined) {
options.stencil = true;
}
if (options.premultipliedAlpha === false) {
this.premultipliedAlpha = false;
}
if (options.xrCompatible === undefined) {
options.xrCompatible = true;
}
this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
// Exceptions
if (navigator && navigator.userAgent) {
var ua = navigator.userAgent;
this.hostInformation.isMobile = ua.indexOf("Mobile") !== -1;
for (var _i = 0, _a = ThinEngine.ExceptionList; _i < _a.length; _i++) {
var exception = _a[_i];
var key = exception.key;
var targets = exception.targets;
var check = new RegExp(key);
if (check.test(ua)) {
if (exception.capture && exception.captureConstraint) {
var capture = exception.capture;
var constraint = exception.captureConstraint;
var regex = new RegExp(capture);
var matches_1 = regex.exec(ua);
if (matches_1 && matches_1.length > 0) {
var capturedValue = parseInt(matches_1[matches_1.length - 1]);
if (capturedValue >= constraint) {
continue;
}
}
}
for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
var target = targets_1[_b];
switch (target) {
case "uniformBuffer":
this.disableUniformBuffers = true;
break;
case "vao":
this.disableVertexArrayObjects = true;
break;
}
}
}
}
}
// Context lost
if (!this._doNotHandleContextLost) {
this._onContextLost = function (evt) {
evt.preventDefault();
_this._contextWasLost = true;
_Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Warn("WebGL context lost.");
_this.onContextLostObservable.notifyObservers(_this);
};
this._onContextRestored = function () {
// Adding a timeout to avoid race condition at browser level
setTimeout(function () {
// Rebuild gl context
_this._initGLContext();
// Rebuild effects
_this._rebuildEffects();
// Rebuild textures
_this._rebuildInternalTextures();
// Rebuild buffers
_this._rebuildBuffers();
// Cache
_this.wipeCaches(true);
_Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Warn("WebGL context successfully restored.");
_this.onContextRestoredObservable.notifyObservers(_this);
_this._contextWasLost = false;
}, 0);
};
canvas.addEventListener("webglcontextlost", this._onContextLost, false);
canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
options.powerPreference = "high-performance";
}
// GL
if (!options.disableWebGL2Support) {
try {
this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
if (this._gl) {
this._webGLVersion = 2.0;
// Prevent weird browsers to lie (yeah that happens!)
if (!this._gl.deleteQuery) {
this._webGLVersion = 1.0;
}
}
}
catch (e) {
// Do nothing
}
}
if (!this._gl) {
if (!canvas) {
throw new Error("The provided canvas is null or undefined.");
}
try {
this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
}
catch (e) {
throw new Error("WebGL not supported");
}
}
if (!this._gl) {
throw new Error("WebGL not supported");
}
}
else {
this._gl = canvasOrContext;
this._renderingCanvas = this._gl.canvas;
if (this._gl.renderbufferStorageMultisample) {
this._webGLVersion = 2.0;
}
var attributes = this._gl.getContextAttributes();
if (attributes) {
options.stencil = attributes.stencil;
}
}
// Ensures a consistent color space unpacking of textures cross browser.
this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
if (options.useHighPrecisionFloats !== undefined) {
this._highPrecisionShadersAllowed = options.useHighPrecisionFloats;
}
// Viewport
var devicePixelRatio = _Misc_domManagement__WEBPACK_IMPORTED_MODULE_10__["DomManagement"].IsWindowObjectExist() ? (window.devicePixelRatio || 1.0) : 1.0;
var limitDeviceRatio = options.limitDeviceRatio || devicePixelRatio;
this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, devicePixelRatio) : 1.0;
this.resize();
this._isStencilEnable = options.stencil ? true : false;
this._initGLContext();
// Prepare buffer pointers
for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
this._currentBufferPointers[i] = new BufferPointer();
}
// Shader processor
if (this.webGLVersion > 1) {
this._shaderProcessor = new _WebGL_webGL2ShaderProcessors__WEBPACK_IMPORTED_MODULE_11__["WebGL2ShaderProcessor"]();
}
// Detect if we are running on a faulty buggy OS.
this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
// Starting with iOS 14, we can trust the browser
var matches = navigator.userAgent.match(/Version\/(\d+)/);
if (matches && matches.length === 2) {
if (parseInt(matches[1]) >= 14) {
this._badOS = false;
}
}
// Detect if we are running on a faulty buggy desktop OS.
this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
this._creationOptions = options;
console.log("Babylon.js v" + ThinEngine.Version + " - " + this.description);
}
Object.defineProperty(ThinEngine, "NpmPackage", {
/**
* Returns the current npm package of the sdk
*/
// Not mixed with Version for tooling purpose.
get: function () {
return "babylonjs@4.2.0-alpha.35";
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine, "Version", {
/**
* Returns the current version of the framework
*/
get: function () {
return "4.2.0-alpha.35";
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "description", {
/**
* Returns a string describing the current engine
*/
get: function () {
var description = "WebGL" + this.webGLVersion;
if (this._caps.parallelShaderCompile) {
description += " - Parallel shader compilation";
}
return description;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine, "ShadersRepository", {
/**
* Gets or sets the relative url used to load shaders if using the engine in non-minified mode
*/
get: function () {
return _Materials_effect__WEBPACK_IMPORTED_MODULE_1__["Effect"].ShadersRepository;
},
set: function (value) {
_Materials_effect__WEBPACK_IMPORTED_MODULE_1__["Effect"].ShadersRepository = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "supportsUniformBuffers", {
/**
* Gets a boolean indicating that the engine supports uniform buffers
* @see https://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
*/
get: function () {
return this.webGLVersion > 1 && !this.disableUniformBuffers;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "_shouldUseHighPrecisionShader", {
/** @hidden */
get: function () {
return !!(this._caps.highPrecisionShaderSupported && this._highPrecisionShadersAllowed);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "needPOTTextures", {
/**
* Gets a boolean indicating that only power of 2 textures are supported
* Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
*/
get: function () {
return this._webGLVersion < 2 || this.forcePOTTextures;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "doNotHandleContextLost", {
/**
* Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
*/
get: function () {
return this._doNotHandleContextLost;
},
set: function (value) {
this._doNotHandleContextLost = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "_supportsHardwareTextureRescaling", {
get: function () {
return false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "framebufferDimensionsObject", {
/**
* sets the object from which width and height will be taken from when getting render width and height
* Will fallback to the gl object
* @param dimensions the framebuffer width and height that will be used.
*/
set: function (dimensions) {
this._framebufferDimensionsObject = dimensions;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "currentViewport", {
/**
* Gets the current viewport
*/
get: function () {
return this._cachedViewport;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "emptyTexture", {
/**
* Gets the default empty texture
*/
get: function () {
if (!this._emptyTexture) {
this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA, false, false, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyTexture;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "emptyTexture3D", {
/**
* Gets the default empty 3D texture
*/
get: function () {
if (!this._emptyTexture3D) {
this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA, false, false, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyTexture3D;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "emptyTexture2DArray", {
/**
* Gets the default empty 2D array texture
*/
get: function () {
if (!this._emptyTexture2DArray) {
this._emptyTexture2DArray = this.createRawTexture2DArray(new Uint8Array(4), 1, 1, 1, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA, false, false, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyTexture2DArray;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "emptyCubeTexture", {
/**
* Gets the default empty cube texture
*/
get: function () {
if (!this._emptyCubeTexture) {
var faceData = new Uint8Array(4);
var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT, false, false, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE);
}
return this._emptyCubeTexture;
},
enumerable: false,
configurable: true
});
ThinEngine.prototype._rebuildInternalTextures = function () {
var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
var internalTexture = currentState_1[_i];
internalTexture._rebuild();
}
};
ThinEngine.prototype._rebuildEffects = function () {
for (var key in this._compiledEffects) {
var effect = this._compiledEffects[key];
effect._prepareEffect();
}
_Materials_effect__WEBPACK_IMPORTED_MODULE_1__["Effect"].ResetCache();
};
/**
* Gets a boolean indicating if all created effects are ready
* @returns true if all effects are ready
*/
ThinEngine.prototype.areAllEffectsReady = function () {
for (var key in this._compiledEffects) {
var effect = this._compiledEffects[key];
if (!effect.isReady()) {
return false;
}
}
return true;
};
ThinEngine.prototype._rebuildBuffers = function () {
// Uniforms
for (var _i = 0, _a = this._uniformBuffers; _i < _a.length; _i++) {
var uniformBuffer = _a[_i];
uniformBuffer._rebuild();
}
};
ThinEngine.prototype._initGLContext = function () {
// Caps
this._caps = {
maxTexturesImageUnits: this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS),
maxCombinedTexturesImageUnits: this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),
maxVertexTextureImageUnits: this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
maxTextureSize: this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE),
maxSamples: this._webGLVersion > 1 ? this._gl.getParameter(this._gl.MAX_SAMPLES) : 1,
maxCubemapTextureSize: this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE),
maxRenderTextureSize: this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE),
maxVertexAttribs: this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS),
maxVaryingVectors: this._gl.getParameter(this._gl.MAX_VARYING_VECTORS),
maxFragmentUniformVectors: this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS),
maxVertexUniformVectors: this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS),
parallelShaderCompile: this._gl.getExtension('KHR_parallel_shader_compile'),
standardDerivatives: this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null),
maxAnisotropy: 1,
astc: this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc'),
s3tc: this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'),
pvrtc: this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
etc1: this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1'),
etc2: this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
this._gl.getExtension('WEBGL_compressed_texture_es3_0'),
textureAnisotropicFilterExtension: this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic'),
uintIndices: this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null,
fragmentDepthSupported: this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null,
highPrecisionShaderSupported: false,
timerQuery: this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query"),
canUseTimestampForTimerQuery: false,
drawBuffersExtension: false,
maxMSAASamples: 1,
colorBufferFloat: this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float'),
textureFloat: (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false,
textureHalfFloat: (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false,
textureHalfFloatRender: false,
textureFloatLinearFiltering: false,
textureFloatRender: false,
textureHalfFloatLinearFiltering: false,
vertexArrayObject: false,
instancedArrays: false,
textureLOD: (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false,
blendMinMax: false,
multiview: this._gl.getExtension('OVR_multiview2'),
oculusMultiview: this._gl.getExtension('OCULUS_multiview'),
depthTextureExtension: false
};
// Infos
this._glVersion = this._gl.getParameter(this._gl.VERSION);
var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
if (rendererInfo != null) {
this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
}
if (!this._glVendor) {
this._glVendor = "Unknown vendor";
}
if (!this._glRenderer) {
this._glRenderer = "Unknown renderer";
}
// Constants
if (this._gl.HALF_FLOAT_OES !== 0x8D61) {
this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
}
if (this._gl.RGBA16F !== 0x881A) {
this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
}
if (this._gl.RGBA32F !== 0x8814) {
this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
}
if (this._gl.DEPTH24_STENCIL8 !== 35056) {
this._gl.DEPTH24_STENCIL8 = 35056;
}
// Extensions
if (this._caps.timerQuery) {
if (this._webGLVersion === 1) {
this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
}
this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
}
this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
// Checks if some of the format renders first to allow the use of webgl inspector.
if (this._webGLVersion > 1) {
if (this._gl.HALF_FLOAT_OES !== 0x140B) {
this._gl.HALF_FLOAT_OES = 0x140B;
}
}
this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
// Draw buffers
if (this._webGLVersion > 1) {
this._caps.drawBuffersExtension = true;
this._caps.maxMSAASamples = this._gl.getParameter(this._gl.MAX_SAMPLES);
}
else {
var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
if (drawBuffersExtension !== null) {
this._caps.drawBuffersExtension = true;
this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
for (var i = 0; i < 16; i++) {
this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
}
}
}
// Depth Texture
if (this._webGLVersion > 1) {
this._caps.depthTextureExtension = true;
}
else {
var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
if (depthTextureExtension != null) {
this._caps.depthTextureExtension = true;
this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
}
}
// Vertex array object
if (this.disableVertexArrayObjects) {
this._caps.vertexArrayObject = false;
}
else if (this._webGLVersion > 1) {
this._caps.vertexArrayObject = true;
}
else {
var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
if (vertexArrayObjectExtension != null) {
this._caps.vertexArrayObject = true;
this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
}
}
// Instances count
if (this._webGLVersion > 1) {
this._caps.instancedArrays = true;
}
else {
var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
if (instanceExtension != null) {
this._caps.instancedArrays = true;
this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
}
else {
this._caps.instancedArrays = false;
}
}
if (this._gl.getShaderPrecisionFormat) {
var vertex_highp = this._gl.getShaderPrecisionFormat(this._gl.VERTEX_SHADER, this._gl.HIGH_FLOAT);
var fragment_highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
if (vertex_highp && fragment_highp) {
this._caps.highPrecisionShaderSupported = vertex_highp.precision !== 0 && fragment_highp.precision !== 0;
}
}
if (this._webGLVersion > 1) {
this._caps.blendMinMax = true;
}
else {
var blendMinMaxExtension = this._gl.getExtension('EXT_blend_minmax');
if (blendMinMaxExtension != null) {
this._caps.blendMinMax = true;
this._gl.MAX = blendMinMaxExtension.MAX_EXT;
this._gl.MIN = blendMinMaxExtension.MIN_EXT;
}
}
// Depth buffer
this._depthCullingState.depthTest = true;
this._depthCullingState.depthFunc = this._gl.LEQUAL;
this._depthCullingState.depthMask = true;
// Texture maps
this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
this._nextFreeTextureSlots.push(slot);
}
};
Object.defineProperty(ThinEngine.prototype, "webGLVersion", {
/**
* Gets version of the current webGL context
*/
get: function () {
return this._webGLVersion;
},
enumerable: false,
configurable: true
});
/**
* Gets a string identifying the name of the class
* @returns "Engine" string
*/
ThinEngine.prototype.getClassName = function () {
return "ThinEngine";
};
Object.defineProperty(ThinEngine.prototype, "isStencilEnable", {
/**
* Returns true if the stencil buffer has been enabled through the creation option of the context.
*/
get: function () {
return this._isStencilEnable;
},
enumerable: false,
configurable: true
});
/** @hidden */
ThinEngine.prototype._prepareWorkingCanvas = function () {
if (this._workingCanvas) {
return;
}
this._workingCanvas = _Misc_canvasGenerator__WEBPACK_IMPORTED_MODULE_14__["CanvasGenerator"].CreateCanvas(1, 1);
var context = this._workingCanvas.getContext("2d");
if (context) {
this._workingContext = context;
}
};
/**
* Reset the texture cache to empty state
*/
ThinEngine.prototype.resetTextureCache = function () {
for (var key in this._boundTexturesCache) {
if (!this._boundTexturesCache.hasOwnProperty(key)) {
continue;
}
this._boundTexturesCache[key] = null;
}
this._currentTextureChannel = -1;
};
/**
* Gets an object containing information about the current webGL context
* @returns an object containing the vender, the renderer and the version of the current webGL context
*/
ThinEngine.prototype.getGlInfo = function () {
return {
vendor: this._glVendor,
renderer: this._glRenderer,
version: this._glVersion
};
};
/**
* Defines the hardware scaling level.
* By default the hardware scaling level is computed from the window device ratio.
* if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
* @param level defines the level to use
*/
ThinEngine.prototype.setHardwareScalingLevel = function (level) {
this._hardwareScalingLevel = level;
this.resize();
};
/**
* Gets the current hardware scaling level.
* By default the hardware scaling level is computed from the window device ratio.
* if level = 1 then the engine will render at the exact resolution of the canvas. If level = 0.5 then the engine will render at twice the size of the canvas.
* @returns a number indicating the current hardware scaling level
*/
ThinEngine.prototype.getHardwareScalingLevel = function () {
return this._hardwareScalingLevel;
};
/**
* Gets the list of loaded textures
* @returns an array containing all loaded textures
*/
ThinEngine.prototype.getLoadedTexturesCache = function () {
return this._internalTexturesCache;
};
/**
* Gets the object containing all engine capabilities
* @returns the EngineCapabilities object
*/
ThinEngine.prototype.getCaps = function () {
return this._caps;
};
/**
* stop executing a render loop function and remove it from the execution array
* @param renderFunction defines the function to be removed. If not provided all functions will be removed.
*/
ThinEngine.prototype.stopRenderLoop = function (renderFunction) {
if (!renderFunction) {
this._activeRenderLoops = [];
return;
}
var index = this._activeRenderLoops.indexOf(renderFunction);
if (index >= 0) {
this._activeRenderLoops.splice(index, 1);
}
};
/** @hidden */
ThinEngine.prototype._renderLoop = function () {
if (!this._contextWasLost) {
var shouldRender = true;
if (!this.renderEvenInBackground && this._windowIsBackground) {
shouldRender = false;
}
if (shouldRender) {
// Start new frame
this.beginFrame();
for (var index = 0; index < this._activeRenderLoops.length; index++) {
var renderFunction = this._activeRenderLoops[index];
renderFunction();
}
// Present
this.endFrame();
}
}
if (this._activeRenderLoops.length > 0) {
this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
}
else {
this._renderingQueueLaunched = false;
}
};
/**
* Gets the HTML canvas attached with the current webGL context
* @returns a HTML canvas
*/
ThinEngine.prototype.getRenderingCanvas = function () {
return this._renderingCanvas;
};
/**
* Gets host window
* @returns the host window object
*/
ThinEngine.prototype.getHostWindow = function () {
if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_10__["DomManagement"].IsWindowObjectExist()) {
return null;
}
if (this._renderingCanvas && this._renderingCanvas.ownerDocument && this._renderingCanvas.ownerDocument.defaultView) {
return this._renderingCanvas.ownerDocument.defaultView;
}
return window;
};
/**
* Gets the current render width
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the current render width
*/
ThinEngine.prototype.getRenderWidth = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.width;
}
return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferWidth : this._gl.drawingBufferWidth;
};
/**
* Gets the current render height
* @param useScreen defines if screen size must be used (or the current render target if any)
* @returns a number defining the current render height
*/
ThinEngine.prototype.getRenderHeight = function (useScreen) {
if (useScreen === void 0) { useScreen = false; }
if (!useScreen && this._currentRenderTarget) {
return this._currentRenderTarget.height;
}
return this._framebufferDimensionsObject ? this._framebufferDimensionsObject.framebufferHeight : this._gl.drawingBufferHeight;
};
/**
* Can be used to override the current requestAnimationFrame requester.
* @hidden
*/
ThinEngine.prototype._queueNewFrame = function (bindedRenderFunction, requester) {
return ThinEngine.QueueNewFrame(bindedRenderFunction, requester);
};
/**
* Register and execute a render loop. The engine can have more than one render function
* @param renderFunction defines the function to continuously execute
*/
ThinEngine.prototype.runRenderLoop = function (renderFunction) {
if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
return;
}
this._activeRenderLoops.push(renderFunction);
if (!this._renderingQueueLaunched) {
this._renderingQueueLaunched = true;
this._boundRenderFunction = this._renderLoop.bind(this);
this._frameHandler = this._queueNewFrame(this._boundRenderFunction, this.getHostWindow());
}
};
/**
* Clear the current render buffer or the current render target (if any is set up)
* @param color defines the color to use
* @param backBuffer defines if the back buffer must be cleared
* @param depth defines if the depth buffer must be cleared
* @param stencil defines if the stencil buffer must be cleared
*/
ThinEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
if (stencil === void 0) { stencil = false; }
this.applyStates();
var mode = 0;
if (backBuffer && color) {
this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
mode |= this._gl.COLOR_BUFFER_BIT;
}
if (depth) {
if (this.useReverseDepthBuffer) {
this._depthCullingState.depthFunc = this._gl.GREATER;
this._gl.clearDepth(0.0);
}
else {
this._gl.clearDepth(1.0);
}
mode |= this._gl.DEPTH_BUFFER_BIT;
}
if (stencil) {
this._gl.clearStencil(0);
mode |= this._gl.STENCIL_BUFFER_BIT;
}
this._gl.clear(mode);
};
/** @hidden */
ThinEngine.prototype._viewport = function (x, y, width, height) {
if (x !== this._viewportCached.x ||
y !== this._viewportCached.y ||
width !== this._viewportCached.z ||
height !== this._viewportCached.w) {
this._viewportCached.x = x;
this._viewportCached.y = y;
this._viewportCached.z = width;
this._viewportCached.w = height;
this._gl.viewport(x, y, width, height);
}
};
/**
* Set the WebGL's viewport
* @param viewport defines the viewport element to be used
* @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
* @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
*/
ThinEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
var width = requiredWidth || this.getRenderWidth();
var height = requiredHeight || this.getRenderHeight();
var x = viewport.x || 0;
var y = viewport.y || 0;
this._cachedViewport = viewport;
this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
};
/**
* Begin a new frame
*/
ThinEngine.prototype.beginFrame = function () {
};
/**
* Enf the current frame
*/
ThinEngine.prototype.endFrame = function () {
// Force a flush in case we are using a bad OS.
if (this._badOS) {
this.flushFramebuffer();
}
};
/**
* Resize the view according to the canvas' size
*/
ThinEngine.prototype.resize = function () {
var width;
var height;
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_10__["DomManagement"].IsWindowObjectExist()) {
width = this._renderingCanvas ? (this._renderingCanvas.clientWidth || this._renderingCanvas.width) : window.innerWidth;
height = this._renderingCanvas ? (this._renderingCanvas.clientHeight || this._renderingCanvas.height) : window.innerHeight;
}
else {
width = this._renderingCanvas ? this._renderingCanvas.width : 100;
height = this._renderingCanvas ? this._renderingCanvas.height : 100;
}
this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
};
/**
* Force a specific size of the canvas
* @param width defines the new canvas' width
* @param height defines the new canvas' height
* @returns true if the size was changed
*/
ThinEngine.prototype.setSize = function (width, height) {
if (!this._renderingCanvas) {
return false;
}
width = width | 0;
height = height | 0;
if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
return false;
}
this._renderingCanvas.width = width;
this._renderingCanvas.height = height;
return true;
};
/**
* Binds the frame buffer to the specified texture.
* @param texture The texture to render to or null for the default canvas
* @param faceIndex The face of the texture to render to in case of cube texture
* @param requiredWidth The width of the target to render to
* @param requiredHeight The height of the target to render to
* @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
* @param lodLevel defines the lod level to bind to the frame buffer
* @param layer defines the 2d array index to bind to frame buffer to
*/
ThinEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, lodLevel, layer) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lodLevel === void 0) { lodLevel = 0; }
if (layer === void 0) { layer = 0; }
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
this._currentRenderTarget = texture;
this._bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
var gl = this._gl;
if (texture.is2DArray) {
gl.framebufferTextureLayer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, texture._webGLTexture, lodLevel, layer);
}
else if (texture.isCube) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
}
var depthStencilTexture = texture._depthStencilTexture;
if (depthStencilTexture) {
var attachment = (depthStencilTexture._generateStencilBuffer) ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
if (texture.is2DArray) {
gl.framebufferTextureLayer(gl.FRAMEBUFFER, attachment, depthStencilTexture._webGLTexture, lodLevel, layer);
}
else if (texture.isCube) {
gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
}
else {
gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, lodLevel);
}
}
if (this._cachedViewport && !forceFullscreenViewport) {
this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
}
else {
if (!requiredWidth) {
requiredWidth = texture.width;
if (lodLevel) {
requiredWidth = requiredWidth / Math.pow(2, lodLevel);
}
}
if (!requiredHeight) {
requiredHeight = texture.height;
if (lodLevel) {
requiredHeight = requiredHeight / Math.pow(2, lodLevel);
}
}
this._viewport(0, 0, requiredWidth, requiredHeight);
}
this.wipeCaches();
};
/** @hidden */
ThinEngine.prototype._bindUnboundFramebuffer = function (framebuffer) {
if (this._currentFramebuffer !== framebuffer) {
this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
this._currentFramebuffer = framebuffer;
}
};
/**
* Unbind the current render target texture from the webGL context
* @param texture defines the render target texture to unbind
* @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
* @param onBeforeUnbind defines a function which will be called before the effective unbind
*/
ThinEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
this._currentRenderTarget = null;
// If MSAA, we need to bitblt back to main texture
var gl = this._gl;
if (texture._MSAAFramebuffer) {
if (texture._textureArray) {
// This texture is part of a MRT texture, we need to treat all attachments
this.unBindMultiColorAttachmentFramebuffer(texture._textureArray, disableGenerateMipMaps, onBeforeUnbind);
return;
}
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
}
if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
gl.generateMipmap(gl.TEXTURE_2D);
this._bindTextureDirectly(gl.TEXTURE_2D, null);
}
if (onBeforeUnbind) {
if (texture._MSAAFramebuffer) {
// Bind the correct framebuffer
this._bindUnboundFramebuffer(texture._framebuffer);
}
onBeforeUnbind();
}
this._bindUnboundFramebuffer(null);
};
/**
* Force a webGL flush (ie. a flush of all waiting webGL commands)
*/
ThinEngine.prototype.flushFramebuffer = function () {
this._gl.flush();
};
/**
* Unbind the current render target and bind the default framebuffer
*/
ThinEngine.prototype.restoreDefaultFramebuffer = function () {
if (this._currentRenderTarget) {
this.unBindFramebuffer(this._currentRenderTarget);
}
else {
this._bindUnboundFramebuffer(null);
}
if (this._cachedViewport) {
this.setViewport(this._cachedViewport);
}
this.wipeCaches();
};
// VBOs
/** @hidden */
ThinEngine.prototype._resetVertexBufferBinding = function () {
this.bindArrayBuffer(null);
this._cachedVertexBuffers = null;
};
/**
* Creates a vertex buffer
* @param data the data for the vertex buffer
* @returns the new WebGL static buffer
*/
ThinEngine.prototype.createVertexBuffer = function (data) {
return this._createVertexBuffer(data, this._gl.STATIC_DRAW);
};
ThinEngine.prototype._createVertexBuffer = function (data, usage) {
var vbo = this._gl.createBuffer();
if (!vbo) {
throw new Error("Unable to create vertex buffer");
}
var dataBuffer = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_12__["WebGLDataBuffer"](vbo);
this.bindArrayBuffer(dataBuffer);
if (data instanceof Array) {
this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
}
else {
this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
}
this._resetVertexBufferBinding();
dataBuffer.references = 1;
return dataBuffer;
};
/**
* Creates a dynamic vertex buffer
* @param data the data for the dynamic vertex buffer
* @returns the new WebGL dynamic buffer
*/
ThinEngine.prototype.createDynamicVertexBuffer = function (data) {
return this._createVertexBuffer(data, this._gl.DYNAMIC_DRAW);
};
ThinEngine.prototype._resetIndexBufferBinding = function () {
this.bindIndexBuffer(null);
this._cachedIndexBuffer = null;
};
/**
* Creates a new index buffer
* @param indices defines the content of the index buffer
* @param updatable defines if the index buffer must be updatable
* @returns a new webGL buffer
*/
ThinEngine.prototype.createIndexBuffer = function (indices, updatable) {
var vbo = this._gl.createBuffer();
var dataBuffer = new _Meshes_WebGL_webGLDataBuffer__WEBPACK_IMPORTED_MODULE_12__["WebGLDataBuffer"](vbo);
if (!vbo) {
throw new Error("Unable to create index buffer");
}
this.bindIndexBuffer(dataBuffer);
var data = this._normalizeIndexData(indices);
this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, data, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
this._resetIndexBufferBinding();
dataBuffer.references = 1;
dataBuffer.is32Bits = (data.BYTES_PER_ELEMENT === 4);
return dataBuffer;
};
ThinEngine.prototype._normalizeIndexData = function (indices) {
if (indices instanceof Uint16Array) {
return indices;
}
// Check 32 bit support
if (this._caps.uintIndices) {
if (indices instanceof Uint32Array) {
return indices;
}
else {
// number[] or Int32Array, check if 32 bit is necessary
for (var index = 0; index < indices.length; index++) {
if (indices[index] >= 65535) {
return new Uint32Array(indices);
}
}
return new Uint16Array(indices);
}
}
// No 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
return new Uint16Array(indices);
};
/**
* Bind a webGL buffer to the webGL context
* @param buffer defines the buffer to bind
*/
ThinEngine.prototype.bindArrayBuffer = function (buffer) {
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
};
/**
* Bind a specific block at a given index in a specific shader program
* @param pipelineContext defines the pipeline context to use
* @param blockName defines the block name
* @param index defines the index where to bind the block
*/
ThinEngine.prototype.bindUniformBlock = function (pipelineContext, blockName, index) {
var program = pipelineContext.program;
var uniformLocation = this._gl.getUniformBlockIndex(program, blockName);
this._gl.uniformBlockBinding(program, uniformLocation, index);
};
ThinEngine.prototype.bindIndexBuffer = function (buffer) {
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
};
ThinEngine.prototype.bindBuffer = function (buffer, target) {
if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
this._gl.bindBuffer(target, buffer ? buffer.underlyingResource : null);
this._currentBoundBuffer[target] = buffer;
}
};
/**
* update the bound buffer with the given data
* @param data defines the data to update
*/
ThinEngine.prototype.updateArrayBuffer = function (data) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
};
ThinEngine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
var pointer = this._currentBufferPointers[indx];
if (!pointer) {
return;
}
var changed = false;
if (!pointer.active) {
changed = true;
pointer.active = true;
pointer.index = indx;
pointer.size = size;
pointer.type = type;
pointer.normalized = normalized;
pointer.stride = stride;
pointer.offset = offset;
pointer.buffer = buffer;
}
else {
if (pointer.buffer !== buffer) {
pointer.buffer = buffer;
changed = true;
}
if (pointer.size !== size) {
pointer.size = size;
changed = true;
}
if (pointer.type !== type) {
pointer.type = type;
changed = true;
}
if (pointer.normalized !== normalized) {
pointer.normalized = normalized;
changed = true;
}
if (pointer.stride !== stride) {
pointer.stride = stride;
changed = true;
}
if (pointer.offset !== offset) {
pointer.offset = offset;
changed = true;
}
}
if (changed || this._vaoRecordInProgress) {
this.bindArrayBuffer(buffer);
this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
}
};
/** @hidden */
ThinEngine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
if (indexBuffer == null) {
return;
}
if (this._cachedIndexBuffer !== indexBuffer) {
this._cachedIndexBuffer = indexBuffer;
this.bindIndexBuffer(indexBuffer);
this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
}
};
ThinEngine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
var attributes = effect.getAttributesNames();
if (!this._vaoRecordInProgress) {
this._unbindVertexArrayObject();
}
this.unbindAllAttributes();
for (var index = 0; index < attributes.length; index++) {
var order = effect.getAttributeLocation(index);
if (order >= 0) {
var vertexBuffer = vertexBuffers[attributes[index]];
if (!vertexBuffer) {
continue;
}
this._gl.enableVertexAttribArray(order);
if (!this._vaoRecordInProgress) {
this._vertexAttribArraysEnabled[order] = true;
}
var buffer = vertexBuffer.getBuffer();
if (buffer) {
this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
if (vertexBuffer.getIsInstanced()) {
this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
if (!this._vaoRecordInProgress) {
this._currentInstanceLocations.push(order);
this._currentInstanceBuffers.push(buffer);
}
}
}
}
}
};
/**
* Records a vertex array object
* @see https://doc.babylonjs.com/features/webgl2#vertex-array-objects
* @param vertexBuffers defines the list of vertex buffers to store
* @param indexBuffer defines the index buffer to store
* @param effect defines the effect to store
* @returns the new vertex array object
*/
ThinEngine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
var vao = this._gl.createVertexArray();
this._vaoRecordInProgress = true;
this._gl.bindVertexArray(vao);
this._mustWipeVertexAttributes = true;
this._bindVertexBuffersAttributes(vertexBuffers, effect);
this.bindIndexBuffer(indexBuffer);
this._vaoRecordInProgress = false;
this._gl.bindVertexArray(null);
return vao;
};
/**
* Bind a specific vertex array object
* @see https://doc.babylonjs.com/features/webgl2#vertex-array-objects
* @param vertexArrayObject defines the vertex array object to bind
* @param indexBuffer defines the index buffer to bind
*/
ThinEngine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
if (this._cachedVertexArrayObject !== vertexArrayObject) {
this._cachedVertexArrayObject = vertexArrayObject;
this._gl.bindVertexArray(vertexArrayObject);
this._cachedVertexBuffers = null;
this._cachedIndexBuffer = null;
this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
this._mustWipeVertexAttributes = true;
}
};
/**
* Bind webGl buffers directly to the webGL context
* @param vertexBuffer defines the vertex buffer to bind
* @param indexBuffer defines the index buffer to bind
* @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
* @param vertexStrideSize defines the vertex stride of the vertex buffer
* @param effect defines the effect associated with the vertex buffer
*/
ThinEngine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
this._cachedVertexBuffers = vertexBuffer;
this._cachedEffectForVertexBuffers = effect;
var attributesCount = effect.getAttributesCount();
this._unbindVertexArrayObject();
this.unbindAllAttributes();
var offset = 0;
for (var index = 0; index < attributesCount; index++) {
if (index < vertexDeclaration.length) {
var order = effect.getAttributeLocation(index);
if (order >= 0) {
this._gl.enableVertexAttribArray(order);
this._vertexAttribArraysEnabled[order] = true;
this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
}
offset += vertexDeclaration[index] * 4;
}
}
}
this._bindIndexBufferWithCache(indexBuffer);
};
ThinEngine.prototype._unbindVertexArrayObject = function () {
if (!this._cachedVertexArrayObject) {
return;
}
this._cachedVertexArrayObject = null;
this._gl.bindVertexArray(null);
};
/**
* Bind a list of vertex buffers to the webGL context
* @param vertexBuffers defines the list of vertex buffers to bind
* @param indexBuffer defines the index buffer to bind
* @param effect defines the effect associated with the vertex buffers
*/
ThinEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
this._cachedVertexBuffers = vertexBuffers;
this._cachedEffectForVertexBuffers = effect;
this._bindVertexBuffersAttributes(vertexBuffers, effect);
}
this._bindIndexBufferWithCache(indexBuffer);
};
/**
* Unbind all instance attributes
*/
ThinEngine.prototype.unbindInstanceAttributes = function () {
var boundBuffer;
for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
var instancesBuffer = this._currentInstanceBuffers[i];
if (boundBuffer != instancesBuffer && instancesBuffer.references) {
boundBuffer = instancesBuffer;
this.bindArrayBuffer(instancesBuffer);
}
var offsetLocation = this._currentInstanceLocations[i];
this._gl.vertexAttribDivisor(offsetLocation, 0);
}
this._currentInstanceBuffers.length = 0;
this._currentInstanceLocations.length = 0;
};
/**
* Release and free the memory of a vertex array object
* @param vao defines the vertex array object to delete
*/
ThinEngine.prototype.releaseVertexArrayObject = function (vao) {
this._gl.deleteVertexArray(vao);
};
/** @hidden */
ThinEngine.prototype._releaseBuffer = function (buffer) {
buffer.references--;
if (buffer.references === 0) {
this._deleteBuffer(buffer);
return true;
}
return false;
};
ThinEngine.prototype._deleteBuffer = function (buffer) {
this._gl.deleteBuffer(buffer.underlyingResource);
};
/**
* Update the content of a webGL buffer used with instanciation and bind it to the webGL context
* @param instancesBuffer defines the webGL buffer to update and bind
* @param data defines the data to store in the buffer
* @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
*/
ThinEngine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
this.bindArrayBuffer(instancesBuffer);
if (data) {
this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
}
if (offsetLocations[0].index !== undefined) {
this.bindInstancesBuffer(instancesBuffer, offsetLocations, true);
}
else {
for (var index = 0; index < 4; index++) {
var offsetLocation = offsetLocations[index];
if (!this._vertexAttribArraysEnabled[offsetLocation]) {
this._gl.enableVertexAttribArray(offsetLocation);
this._vertexAttribArraysEnabled[offsetLocation] = true;
}
this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
this._gl.vertexAttribDivisor(offsetLocation, 1);
this._currentInstanceLocations.push(offsetLocation);
this._currentInstanceBuffers.push(instancesBuffer);
}
}
};
/**
* Bind the content of a webGL buffer used with instantiation
* @param instancesBuffer defines the webGL buffer to bind
* @param attributesInfo defines the offsets or attributes information used to determine where data must be stored in the buffer
* @param computeStride defines Whether to compute the strides from the info or use the default 0
*/
ThinEngine.prototype.bindInstancesBuffer = function (instancesBuffer, attributesInfo, computeStride) {
if (computeStride === void 0) { computeStride = true; }
this.bindArrayBuffer(instancesBuffer);
var stride = 0;
if (computeStride) {
for (var i = 0; i < attributesInfo.length; i++) {
var ai = attributesInfo[i];
stride += ai.attributeSize * 4;
}
}
for (var i = 0; i < attributesInfo.length; i++) {
var ai = attributesInfo[i];
if (ai.index === undefined) {
ai.index = this._currentEffect.getAttributeLocationByName(ai.attributeName);
}
if (ai.index < 0) {
continue;
}
if (!this._vertexAttribArraysEnabled[ai.index]) {
this._gl.enableVertexAttribArray(ai.index);
this._vertexAttribArraysEnabled[ai.index] = true;
}
this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attributeType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
this._gl.vertexAttribDivisor(ai.index, ai.divisor === undefined ? 1 : ai.divisor);
this._currentInstanceLocations.push(ai.index);
this._currentInstanceBuffers.push(instancesBuffer);
}
};
/**
* Disable the instance attribute corresponding to the name in parameter
* @param name defines the name of the attribute to disable
*/
ThinEngine.prototype.disableInstanceAttributeByName = function (name) {
if (!this._currentEffect) {
return;
}
var attributeLocation = this._currentEffect.getAttributeLocationByName(name);
this.disableInstanceAttribute(attributeLocation);
};
/**
* Disable the instance attribute corresponding to the location in parameter
* @param attributeLocation defines the attribute location of the attribute to disable
*/
ThinEngine.prototype.disableInstanceAttribute = function (attributeLocation) {
var shouldClean = false;
var index;
while ((index = this._currentInstanceLocations.indexOf(attributeLocation)) !== -1) {
this._currentInstanceLocations.splice(index, 1);
this._currentInstanceBuffers.splice(index, 1);
shouldClean = true;
index = this._currentInstanceLocations.indexOf(attributeLocation);
}
if (shouldClean) {
this._gl.vertexAttribDivisor(attributeLocation, 0);
this.disableAttributeByIndex(attributeLocation);
}
};
/**
* Disable the attribute corresponding to the location in parameter
* @param attributeLocation defines the attribute location of the attribute to disable
*/
ThinEngine.prototype.disableAttributeByIndex = function (attributeLocation) {
this._gl.disableVertexAttribArray(attributeLocation);
this._vertexAttribArraysEnabled[attributeLocation] = false;
this._currentBufferPointers[attributeLocation].active = false;
};
/**
* Send a draw order
* @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
* @param indexStart defines the starting index
* @param indexCount defines the number of index to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
ThinEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
this.drawElementsType(useTriangles ? _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TriangleFillMode : _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_WireFrameFillMode, indexStart, indexCount, instancesCount);
};
/**
* Draw a list of points
* @param verticesStart defines the index of first vertex to draw
* @param verticesCount defines the count of vertices to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
ThinEngine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
this.drawArraysType(_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_PointFillMode, verticesStart, verticesCount, instancesCount);
};
/**
* Draw a list of unindexed primitives
* @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
* @param verticesStart defines the index of first vertex to draw
* @param verticesCount defines the count of vertices to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
ThinEngine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
this.drawArraysType(useTriangles ? _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TriangleFillMode : _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_WireFrameFillMode, verticesStart, verticesCount, instancesCount);
};
/**
* Draw a list of indexed primitives
* @param fillMode defines the primitive to use
* @param indexStart defines the starting index
* @param indexCount defines the number of index to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
ThinEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
// Apply states
this.applyStates();
this._reportDrawCall();
// Render
var drawMode = this._drawMode(fillMode);
var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
var mult = this._uintIndicesCurrentlySet ? 4 : 2;
if (instancesCount) {
this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
}
else {
this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
}
};
/**
* Draw a list of unindexed primitives
* @param fillMode defines the primitive to use
* @param verticesStart defines the index of first vertex to draw
* @param verticesCount defines the count of vertices to draw
* @param instancesCount defines the number of instances to draw (if instanciation is enabled)
*/
ThinEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
// Apply states
this.applyStates();
this._reportDrawCall();
var drawMode = this._drawMode(fillMode);
if (instancesCount) {
this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
}
else {
this._gl.drawArrays(drawMode, verticesStart, verticesCount);
}
};
ThinEngine.prototype._drawMode = function (fillMode) {
switch (fillMode) {
// Triangle views
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TriangleFillMode:
return this._gl.TRIANGLES;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_PointFillMode:
return this._gl.POINTS;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_WireFrameFillMode:
return this._gl.LINES;
// Draw modes
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_PointListDrawMode:
return this._gl.POINTS;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_LineListDrawMode:
return this._gl.LINES;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_LineLoopDrawMode:
return this._gl.LINE_LOOP;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_LineStripDrawMode:
return this._gl.LINE_STRIP;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TriangleStripDrawMode:
return this._gl.TRIANGLE_STRIP;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].MATERIAL_TriangleFanDrawMode:
return this._gl.TRIANGLE_FAN;
default:
return this._gl.TRIANGLES;
}
};
/** @hidden */
ThinEngine.prototype._reportDrawCall = function () {
// Will be implemented by children
};
// Shaders
/** @hidden */
ThinEngine.prototype._releaseEffect = function (effect) {
if (this._compiledEffects[effect._key]) {
delete this._compiledEffects[effect._key];
this._deletePipelineContext(effect.getPipelineContext());
}
};
/** @hidden */
ThinEngine.prototype._deletePipelineContext = function (pipelineContext) {
var webGLPipelineContext = pipelineContext;
if (webGLPipelineContext && webGLPipelineContext.program) {
webGLPipelineContext.program.__SPECTOR_rebuildProgram = null;
this._gl.deleteProgram(webGLPipelineContext.program);
}
};
/**
* Create a new effect (used to store vertex/fragment shaders)
* @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
* @param attributesNamesOrOptions defines either a list of attribute names or an IEffectCreationOptions object
* @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
* @param samplers defines an array of string used to represent textures
* @param defines defines the string containing the defines to use to compile the shaders
* @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
* @param onCompiled defines a function to call when the effect creation is successful
* @param onError defines a function to call when the effect creation has failed
* @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
* @returns the new Effect
*/
ThinEngine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
var vertex = baseName.vertexElement || baseName.vertex || baseName.vertexToken || baseName;
var fragment = baseName.fragmentElement || baseName.fragment || baseName.fragmentToken || baseName;
var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
if (this._compiledEffects[name]) {
var compiledEffect = this._compiledEffects[name];
if (onCompiled && compiledEffect.isReady()) {
onCompiled(compiledEffect);
}
return compiledEffect;
}
var effect = new _Materials_effect__WEBPACK_IMPORTED_MODULE_1__["Effect"](baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
effect._key = name;
this._compiledEffects[name] = effect;
return effect;
};
ThinEngine._ConcatenateShader = function (source, defines, shaderVersion) {
if (shaderVersion === void 0) { shaderVersion = ""; }
return shaderVersion + (defines ? defines + "\n" : "") + source;
};
ThinEngine.prototype._compileShader = function (source, type, defines, shaderVersion) {
return this._compileRawShader(ThinEngine._ConcatenateShader(source, defines, shaderVersion), type);
};
ThinEngine.prototype._compileRawShader = function (source, type) {
var gl = this._gl;
var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
if (!shader) {
throw new Error("Something went wrong while compile the shader.");
}
gl.shaderSource(shader, source);
gl.compileShader(shader);
return shader;
};
/** @hidden */
ThinEngine.prototype._getShaderSource = function (shader) {
return this._gl.getShaderSource(shader);
};
/**
* Directly creates a webGL program
* @param pipelineContext defines the pipeline context to attach to
* @param vertexCode defines the vertex shader code to use
* @param fragmentCode defines the fragment shader code to use
* @param context defines the webGL context to use (if not set, the current one will be used)
* @param transformFeedbackVaryings defines the list of transform feedback varyings to use
* @returns the new webGL program
*/
ThinEngine.prototype.createRawShaderProgram = function (pipelineContext, vertexCode, fragmentCode, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
context = context || this._gl;
var vertexShader = this._compileRawShader(vertexCode, "vertex");
var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
return this._createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
};
/**
* Creates a webGL program
* @param pipelineContext defines the pipeline context to attach to
* @param vertexCode defines the vertex shader code to use
* @param fragmentCode defines the fragment shader code to use
* @param defines defines the string containing the defines to use to compile the shaders
* @param context defines the webGL context to use (if not set, the current one will be used)
* @param transformFeedbackVaryings defines the list of transform feedback varyings to use
* @returns the new webGL program
*/
ThinEngine.prototype.createShaderProgram = function (pipelineContext, vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
context = context || this._gl;
var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
return this._createShaderProgram(pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings);
};
/**
* Creates a new pipeline context
* @returns the new pipeline
*/
ThinEngine.prototype.createPipelineContext = function () {
var pipelineContext = new _WebGL_webGLPipelineContext__WEBPACK_IMPORTED_MODULE_13__["WebGLPipelineContext"]();
pipelineContext.engine = this;
if (this._caps.parallelShaderCompile) {
pipelineContext.isParallelCompiled = true;
}
return pipelineContext;
};
ThinEngine.prototype._createShaderProgram = function (pipelineContext, vertexShader, fragmentShader, context, transformFeedbackVaryings) {
if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
var shaderProgram = context.createProgram();
pipelineContext.program = shaderProgram;
if (!shaderProgram) {
throw new Error("Unable to create program");
}
context.attachShader(shaderProgram, vertexShader);
context.attachShader(shaderProgram, fragmentShader);
context.linkProgram(shaderProgram);
pipelineContext.context = context;
pipelineContext.vertexShader = vertexShader;
pipelineContext.fragmentShader = fragmentShader;
if (!pipelineContext.isParallelCompiled) {
this._finalizePipelineContext(pipelineContext);
}
return shaderProgram;
};
ThinEngine.prototype._finalizePipelineContext = function (pipelineContext) {
var context = pipelineContext.context;
var vertexShader = pipelineContext.vertexShader;
var fragmentShader = pipelineContext.fragmentShader;
var program = pipelineContext.program;
var linked = context.getProgramParameter(program, context.LINK_STATUS);
if (!linked) { // Get more info
// Vertex
if (!this._gl.getShaderParameter(vertexShader, this._gl.COMPILE_STATUS)) {
var log = this._gl.getShaderInfoLog(vertexShader);
if (log) {
pipelineContext.vertexCompilationError = log;
throw new Error("VERTEX SHADER " + log);
}
}
// Fragment
if (!this._gl.getShaderParameter(fragmentShader, this._gl.COMPILE_STATUS)) {
var log = this._gl.getShaderInfoLog(fragmentShader);
if (log) {
pipelineContext.fragmentCompilationError = log;
throw new Error("FRAGMENT SHADER " + log);
}
}
var error = context.getProgramInfoLog(program);
if (error) {
pipelineContext.programLinkError = error;
throw new Error(error);
}
}
if (this.validateShaderPrograms) {
context.validateProgram(program);
var validated = context.getProgramParameter(program, context.VALIDATE_STATUS);
if (!validated) {
var error = context.getProgramInfoLog(program);
if (error) {
pipelineContext.programValidationError = error;
throw new Error(error);
}
}
}
context.deleteShader(vertexShader);
context.deleteShader(fragmentShader);
pipelineContext.vertexShader = undefined;
pipelineContext.fragmentShader = undefined;
if (pipelineContext.onCompiled) {
pipelineContext.onCompiled();
pipelineContext.onCompiled = undefined;
}
};
/** @hidden */
ThinEngine.prototype._preparePipelineContext = function (pipelineContext, vertexSourceCode, fragmentSourceCode, createAsRaw, rebuildRebind, defines, transformFeedbackVaryings) {
var webGLRenderingState = pipelineContext;
if (createAsRaw) {
webGLRenderingState.program = this.createRawShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, undefined, transformFeedbackVaryings);
}
else {
webGLRenderingState.program = this.createShaderProgram(webGLRenderingState, vertexSourceCode, fragmentSourceCode, defines, undefined, transformFeedbackVaryings);
}
webGLRenderingState.program.__SPECTOR_rebuildProgram = rebuildRebind;
};
/** @hidden */
ThinEngine.prototype._isRenderingStateCompiled = function (pipelineContext) {
var webGLPipelineContext = pipelineContext;
if (this._gl.getProgramParameter(webGLPipelineContext.program, this._caps.parallelShaderCompile.COMPLETION_STATUS_KHR)) {
this._finalizePipelineContext(webGLPipelineContext);
return true;
}
return false;
};
/** @hidden */
ThinEngine.prototype._executeWhenRenderingStateIsCompiled = function (pipelineContext, action) {
var webGLPipelineContext = pipelineContext;
if (!webGLPipelineContext.isParallelCompiled) {
action();
return;
}
var oldHandler = webGLPipelineContext.onCompiled;
if (oldHandler) {
webGLPipelineContext.onCompiled = function () {
oldHandler();
action();
};
}
else {
webGLPipelineContext.onCompiled = action;
}
};
/**
* Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
* @param pipelineContext defines the pipeline context to use
* @param uniformsNames defines the list of uniform names
* @returns an array of webGL uniform locations
*/
ThinEngine.prototype.getUniforms = function (pipelineContext, uniformsNames) {
var results = new Array();
var webGLPipelineContext = pipelineContext;
for (var index = 0; index < uniformsNames.length; index++) {
results.push(this._gl.getUniformLocation(webGLPipelineContext.program, uniformsNames[index]));
}
return results;
};
/**
* Gets the lsit of active attributes for a given webGL program
* @param pipelineContext defines the pipeline context to use
* @param attributesNames defines the list of attribute names to get
* @returns an array of indices indicating the offset of each attribute
*/
ThinEngine.prototype.getAttributes = function (pipelineContext, attributesNames) {
var results = [];
var webGLPipelineContext = pipelineContext;
for (var index = 0; index < attributesNames.length; index++) {
try {
results.push(this._gl.getAttribLocation(webGLPipelineContext.program, attributesNames[index]));
}
catch (e) {
results.push(-1);
}
}
return results;
};
/**
* Activates an effect, mkaing it the current one (ie. the one used for rendering)
* @param effect defines the effect to activate
*/
ThinEngine.prototype.enableEffect = function (effect) {
if (!effect || effect === this._currentEffect) {
return;
}
// Use program
this.bindSamplers(effect);
this._currentEffect = effect;
if (effect.onBind) {
effect.onBind(effect);
}
if (effect._onBindObservable) {
effect._onBindObservable.notifyObservers(effect);
}
};
/**
* Set the value of an uniform to a number (int)
* @param uniform defines the webGL uniform location where to store the value
* @param value defines the int number to store
*/
ThinEngine.prototype.setInt = function (uniform, value) {
if (!uniform) {
return;
}
this._gl.uniform1i(uniform, value);
};
/**
* Set the value of an uniform to an array of int32
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
ThinEngine.prototype.setIntArray = function (uniform, array) {
if (!uniform) {
return;
}
this._gl.uniform1iv(uniform, array);
};
/**
* Set the value of an uniform to an array of int32 (stored as vec2)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
ThinEngine.prototype.setIntArray2 = function (uniform, array) {
if (!uniform || array.length % 2 !== 0) {
return;
}
this._gl.uniform2iv(uniform, array);
};
/**
* Set the value of an uniform to an array of int32 (stored as vec3)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
ThinEngine.prototype.setIntArray3 = function (uniform, array) {
if (!uniform || array.length % 3 !== 0) {
return;
}
this._gl.uniform3iv(uniform, array);
};
/**
* Set the value of an uniform to an array of int32 (stored as vec4)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of int32 to store
*/
ThinEngine.prototype.setIntArray4 = function (uniform, array) {
if (!uniform || array.length % 4 !== 0) {
return;
}
this._gl.uniform4iv(uniform, array);
};
/**
* Set the value of an uniform to an array of number
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
ThinEngine.prototype.setArray = function (uniform, array) {
if (!uniform) {
return;
}
this._gl.uniform1fv(uniform, array);
};
/**
* Set the value of an uniform to an array of number (stored as vec2)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
ThinEngine.prototype.setArray2 = function (uniform, array) {
if (!uniform || array.length % 2 !== 0) {
return;
}
this._gl.uniform2fv(uniform, array);
};
/**
* Set the value of an uniform to an array of number (stored as vec3)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
ThinEngine.prototype.setArray3 = function (uniform, array) {
if (!uniform || array.length % 3 !== 0) {
return;
}
this._gl.uniform3fv(uniform, array);
};
/**
* Set the value of an uniform to an array of number (stored as vec4)
* @param uniform defines the webGL uniform location where to store the value
* @param array defines the array of number to store
*/
ThinEngine.prototype.setArray4 = function (uniform, array) {
if (!uniform || array.length % 4 !== 0) {
return;
}
this._gl.uniform4fv(uniform, array);
};
/**
* Set the value of an uniform to an array of float32 (stored as matrices)
* @param uniform defines the webGL uniform location where to store the value
* @param matrices defines the array of float32 to store
*/
ThinEngine.prototype.setMatrices = function (uniform, matrices) {
if (!uniform) {
return;
}
this._gl.uniformMatrix4fv(uniform, false, matrices);
};
/**
* Set the value of an uniform to a matrix (3x3)
* @param uniform defines the webGL uniform location where to store the value
* @param matrix defines the Float32Array representing the 3x3 matrix to store
*/
ThinEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
if (!uniform) {
return;
}
this._gl.uniformMatrix3fv(uniform, false, matrix);
};
/**
* Set the value of an uniform to a matrix (2x2)
* @param uniform defines the webGL uniform location where to store the value
* @param matrix defines the Float32Array representing the 2x2 matrix to store
*/
ThinEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
if (!uniform) {
return;
}
this._gl.uniformMatrix2fv(uniform, false, matrix);
};
/**
* Set the value of an uniform to a number (float)
* @param uniform defines the webGL uniform location where to store the value
* @param value defines the float number to store
*/
ThinEngine.prototype.setFloat = function (uniform, value) {
if (!uniform) {
return;
}
this._gl.uniform1f(uniform, value);
};
/**
* Set the value of an uniform to a vec2
* @param uniform defines the webGL uniform location where to store the value
* @param x defines the 1st component of the value
* @param y defines the 2nd component of the value
*/
ThinEngine.prototype.setFloat2 = function (uniform, x, y) {
if (!uniform) {
return;
}
this._gl.uniform2f(uniform, x, y);
};
/**
* Set the value of an uniform to a vec3
* @param uniform defines the webGL uniform location where to store the value
* @param x defines the 1st component of the value
* @param y defines the 2nd component of the value
* @param z defines the 3rd component of the value
*/
ThinEngine.prototype.setFloat3 = function (uniform, x, y, z) {
if (!uniform) {
return;
}
this._gl.uniform3f(uniform, x, y, z);
};
/**
* Set the value of an uniform to a vec4
* @param uniform defines the webGL uniform location where to store the value
* @param x defines the 1st component of the value
* @param y defines the 2nd component of the value
* @param z defines the 3rd component of the value
* @param w defines the 4th component of the value
*/
ThinEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
if (!uniform) {
return;
}
this._gl.uniform4f(uniform, x, y, z, w);
};
// States
/**
* Apply all cached states (depth, culling, stencil and alpha)
*/
ThinEngine.prototype.applyStates = function () {
this._depthCullingState.apply(this._gl);
this._stencilState.apply(this._gl);
this._alphaState.apply(this._gl);
if (this._colorWriteChanged) {
this._colorWriteChanged = false;
var enable = this._colorWrite;
this._gl.colorMask(enable, enable, enable, enable);
}
};
/**
* Enable or disable color writing
* @param enable defines the state to set
*/
ThinEngine.prototype.setColorWrite = function (enable) {
if (enable !== this._colorWrite) {
this._colorWriteChanged = true;
this._colorWrite = enable;
}
};
/**
* Gets a boolean indicating if color writing is enabled
* @returns the current color writing state
*/
ThinEngine.prototype.getColorWrite = function () {
return this._colorWrite;
};
Object.defineProperty(ThinEngine.prototype, "depthCullingState", {
/**
* Gets the depth culling state manager
*/
get: function () {
return this._depthCullingState;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "alphaState", {
/**
* Gets the alpha state manager
*/
get: function () {
return this._alphaState;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ThinEngine.prototype, "stencilState", {
/**
* Gets the stencil state manager
*/
get: function () {
return this._stencilState;
},
enumerable: false,
configurable: true
});
// Textures
/**
* Clears the list of texture accessible through engine.
* This can help preventing texture load conflict due to name collision.
*/
ThinEngine.prototype.clearInternalTexturesCache = function () {
this._internalTexturesCache = [];
};
/**
* Force the entire cache to be cleared
* You should not have to use this function unless your engine needs to share the webGL context with another engine
* @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
*/
ThinEngine.prototype.wipeCaches = function (bruteForce) {
if (this.preventCacheWipeBetweenFrames && !bruteForce) {
return;
}
this._currentEffect = null;
this._viewportCached.x = 0;
this._viewportCached.y = 0;
this._viewportCached.z = 0;
this._viewportCached.w = 0;
// Done before in case we clean the attributes
this._unbindVertexArrayObject();
if (bruteForce) {
this._currentProgram = null;
this.resetTextureCache();
this._stencilState.reset();
this._depthCullingState.reset();
this._depthCullingState.depthFunc = this._gl.LEQUAL;
this._alphaState.reset();
this._alphaMode = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].ALPHA_ADD;
this._alphaEquation = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].ALPHA_DISABLE;
this._colorWrite = true;
this._colorWriteChanged = true;
this._unpackFlipYCached = null;
this._gl.pixelStorei(this._gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, this._gl.NONE);
this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
this._mustWipeVertexAttributes = true;
this.unbindAllAttributes();
}
this._resetVertexBufferBinding();
this._cachedIndexBuffer = null;
this._cachedEffectForVertexBuffers = null;
this.bindIndexBuffer(null);
};
/** @hidden */
ThinEngine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
var gl = this._gl;
var magFilter = gl.NEAREST;
var minFilter = gl.NEAREST;
switch (samplingMode) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
}
else {
minFilter = gl.LINEAR;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
}
else {
minFilter = gl.LINEAR;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_NEAREST_MIPLINEAR:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_LINEAR;
}
else {
minFilter = gl.NEAREST;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_NEAREST_MIPNEAREST:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_NEAREST;
}
else {
minFilter = gl.NEAREST;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_LINEAR_MIPNEAREST:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_NEAREST;
}
else {
minFilter = gl.LINEAR;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_LINEAR_MIPLINEAR:
magFilter = gl.NEAREST;
if (generateMipMaps) {
minFilter = gl.LINEAR_MIPMAP_LINEAR;
}
else {
minFilter = gl.LINEAR;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_LINEAR:
magFilter = gl.NEAREST;
minFilter = gl.LINEAR;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_NEAREST:
magFilter = gl.NEAREST;
minFilter = gl.NEAREST;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_NEAREST_MIPNEAREST:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_NEAREST;
}
else {
minFilter = gl.NEAREST;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_NEAREST_MIPLINEAR:
magFilter = gl.LINEAR;
if (generateMipMaps) {
minFilter = gl.NEAREST_MIPMAP_LINEAR;
}
else {
minFilter = gl.NEAREST;
}
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_LINEAR:
magFilter = gl.LINEAR;
minFilter = gl.LINEAR;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_NEAREST:
magFilter = gl.LINEAR;
minFilter = gl.NEAREST;
break;
}
return {
min: minFilter,
mag: magFilter
};
};
/** @hidden */
ThinEngine.prototype._createTexture = function () {
var texture = this._gl.createTexture();
if (!texture) {
throw new Error("Unable to create texture");
}
return texture;
};
/**
* Usually called from Texture.ts.
* Passed information to create a WebGLTexture
* @param url defines a value which contains one of the following:
* * A conventional http URL, e.g. 'http://...' or 'file://...'
* * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
* * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
* @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
* @param invertY when true, image is flipped when loaded. You probably want true. Certain compressed textures may invert this if their default is inverted (eg. ktx)
* @param scene needed for loading to the correct scene
* @param samplingMode mode with should be used sample / access the texture (Default: Texture.TRILINEAR_SAMPLINGMODE)
* @param onLoad optional callback to be called upon successful completion
* @param onError optional callback to be called upon failure
* @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
* @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
* @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
* @param forcedExtension defines the extension to use to pick the right loader
* @param mimeType defines an optional mime type
* @returns a InternalTexture for assignment back into BABYLON.Texture
*/
ThinEngine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension, mimeType) {
var _this = this;
if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; }
if (onLoad === void 0) { onLoad = null; }
if (onError === void 0) { onError = null; }
if (buffer === void 0) { buffer = null; }
if (fallback === void 0) { fallback = null; }
if (format === void 0) { format = null; }
if (forcedExtension === void 0) { forcedExtension = null; }
url = url || "";
var fromData = url.substr(0, 5) === "data:";
var fromBlob = url.substr(0, 5) === "blob:";
var isBase64 = fromData && url.indexOf(";base64,") !== -1;
var texture = fallback ? fallback : new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_8__["InternalTexture"](this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_8__["InternalTextureSource"].Url);
var originalUrl = url;
if (this._transformTextureUrl && !isBase64 && !fallback && !buffer) {
url = this._transformTextureUrl(url);
}
// establish the file extension, if possible
var lastDot = url.lastIndexOf('.');
var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
var loader = null;
// Remove query string
var queryStringIndex = extension.indexOf("?");
if (queryStringIndex > -1) {
extension = extension.split("?")[0];
}
for (var _i = 0, _a = ThinEngine._TextureLoaders; _i < _a.length; _i++) {
var availableLoader = _a[_i];
if (availableLoader.canLoad(extension, mimeType)) {
loader = availableLoader;
break;
}
}
if (scene) {
scene._addPendingData(texture);
}
texture.url = url;
texture.generateMipMaps = !noMipmap;
texture.samplingMode = samplingMode;
texture.invertY = invertY;
if (!this._doNotHandleContextLost) {
// Keep a link to the buffer only if we plan to handle context lost
texture._buffer = buffer;
}
var onLoadObserver = null;
if (onLoad && !fallback) {
onLoadObserver = texture.onLoadedObservable.add(onLoad);
}
if (!fallback) {
this._internalTexturesCache.push(texture);
}
var onInternalError = function (message, exception) {
if (scene) {
scene._removePendingData(texture);
}
if (url === originalUrl) {
if (onLoadObserver) {
texture.onLoadedObservable.remove(onLoadObserver);
}
if (_engineStore__WEBPACK_IMPORTED_MODULE_0__["EngineStore"].UseFallbackTexture) {
_this.createTexture(_engineStore__WEBPACK_IMPORTED_MODULE_0__["EngineStore"].FallbackTexture, noMipmap, texture.invertY, scene, samplingMode, null, onError, buffer, texture);
}
if (onError) {
onError((message || "Unknown error") + (_engineStore__WEBPACK_IMPORTED_MODULE_0__["EngineStore"].UseFallbackTexture ? " - Fallback texture was used" : ""), exception);
}
}
else {
// fall back to the original url if the transformed url fails to load
_Misc_logger__WEBPACK_IMPORTED_MODULE_9__["Logger"].Warn("Failed to load " + url + ", falling back to " + originalUrl);
_this.createTexture(originalUrl, noMipmap, texture.invertY, scene, samplingMode, onLoad, onError, buffer, texture, format, forcedExtension, mimeType);
}
};
// processing for non-image formats
if (loader) {
var callback_1 = function (data) {
loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done, loadFailed) {
if (loadFailed) {
onInternalError("TextureLoader failed to load data");
}
else {
_this._prepareWebGLTexture(texture, scene, width, height, texture.invertY, !loadMipmap, isCompressed, function () {
done();
return false;
}, samplingMode);
}
});
};
if (!buffer) {
this._loadFile(url, function (data) { return callback_1(new Uint8Array(data)); }, undefined, scene ? scene.offlineProvider : undefined, true, function (request, exception) {
onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
});
}
else {
if (buffer instanceof ArrayBuffer) {
callback_1(new Uint8Array(buffer));
}
else if (ArrayBuffer.isView(buffer)) {
callback_1(buffer);
}
else {
if (onError) {
onError("Unable to load: only ArrayBuffer or ArrayBufferView is supported", null);
}
}
}
}
else {
var onload_1 = function (img) {
if (fromBlob && !_this._doNotHandleContextLost) {
// We need to store the image if we need to rebuild the texture
// in case of a webgl context lost
texture._buffer = img;
}
_this._prepareWebGLTexture(texture, scene, img.width, img.height, texture.invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
var gl = _this._gl;
var isPot = (img.width === potWidth && img.height === potHeight);
var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
if (isPot) {
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
return false;
}
var maxTextureSize = _this._caps.maxTextureSize;
if (img.width > maxTextureSize || img.height > maxTextureSize || !_this._supportsHardwareTextureRescaling) {
_this._prepareWorkingCanvas();
if (!_this._workingCanvas || !_this._workingContext) {
return false;
}
_this._workingCanvas.width = potWidth;
_this._workingCanvas.height = potHeight;
_this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
texture.width = potWidth;
texture.height = potHeight;
return false;
}
else {
// Using shaders when possible to rescale because canvas.drawImage is lossy
var source_1 = new _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_8__["InternalTexture"](_this, _Materials_Textures_internalTexture__WEBPACK_IMPORTED_MODULE_8__["InternalTextureSource"].Temp);
_this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
_this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
_this._releaseTexture(source_1);
_this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
continuationCallback();
});
}
return true;
}, samplingMode);
};
if (!fromData || isBase64) {
if (buffer && (buffer.decoding || buffer.close)) {
onload_1(buffer);
}
else {
ThinEngine._FileToolsLoadImage(url, onload_1, onInternalError, scene ? scene.offlineProvider : null, mimeType);
}
}
else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || ArrayBuffer.isView(buffer) || buffer instanceof Blob) {
ThinEngine._FileToolsLoadImage(buffer, onload_1, onInternalError, scene ? scene.offlineProvider : null, mimeType);
}
else if (buffer) {
onload_1(buffer);
}
}
return texture;
};
/**
* Loads an image as an HTMLImageElement.
* @param input url string, ArrayBuffer, or Blob to load
* @param onLoad callback called when the image successfully loads
* @param onError callback called when the image fails to load
* @param offlineProvider offline provider for caching
* @param mimeType optional mime type
* @returns the HTMLImageElement of the loaded image
* @hidden
*/
ThinEngine._FileToolsLoadImage = function (input, onLoad, onError, offlineProvider, mimeType) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__["_DevTools"].WarnImport("FileTools");
};
/**
* @hidden
*/
ThinEngine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
};
/**
* Creates a raw texture
* @param data defines the data to store in the texture
* @param width defines the width of the texture
* @param height defines the height of the texture
* @param format defines the format of the data
* @param generateMipMaps defines if the engine should generate the mip levels
* @param invertY defines if data must be stored with Y axis inverted
* @param samplingMode defines the required sampling mode (Texture.NEAREST_SAMPLINGMODE by default)
* @param compression defines the compression used (null by default)
* @param type defines the type fo the data (Engine.TEXTURETYPE_UNSIGNED_INT by default)
* @returns the raw texture inside an InternalTexture
*/
ThinEngine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
if (compression === void 0) { compression = null; }
if (type === void 0) { type = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__["_DevTools"].WarnImport("Engine.RawTexture");
};
/**
* Creates a new raw cube texture
* @param data defines the array of data to use to create each face
* @param size defines the size of the textures
* @param format defines the format of the data
* @param type defines the type of the data (like Engine.TEXTURETYPE_UNSIGNED_INT)
* @param generateMipMaps defines if the engine should generate the mip levels
* @param invertY defines if data must be stored with Y axis inverted
* @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
* @param compression defines the compression used (null by default)
* @returns the cube texture as an InternalTexture
*/
ThinEngine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
if (compression === void 0) { compression = null; }
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__["_DevTools"].WarnImport("Engine.RawTexture");
};
/**
* Creates a new raw 3D texture
* @param data defines the data used to create the texture
* @param width defines the width of the texture
* @param height defines the height of the texture
* @param depth defines the depth of the texture
* @param format defines the format of the texture
* @param generateMipMaps defines if the engine must generate mip levels
* @param invertY defines if data must be stored with Y axis inverted
* @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
* @param compression defines the compressed used (can be null)
* @param textureType defines the compressed used (can be null)
* @returns a new raw 3D texture (stored in an InternalTexture)
*/
ThinEngine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
if (compression === void 0) { compression = null; }
if (textureType === void 0) { textureType = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__["_DevTools"].WarnImport("Engine.RawTexture");
};
/**
* Creates a new raw 2D array texture
* @param data defines the data used to create the texture
* @param width defines the width of the texture
* @param height defines the height of the texture
* @param depth defines the number of layers of the texture
* @param format defines the format of the texture
* @param generateMipMaps defines if the engine must generate mip levels
* @param invertY defines if data must be stored with Y axis inverted
* @param samplingMode defines the required sampling mode (like Texture.NEAREST_SAMPLINGMODE)
* @param compression defines the compressed used (can be null)
* @param textureType defines the compressed used (can be null)
* @returns a new raw 2D array texture (stored in an InternalTexture)
*/
ThinEngine.prototype.createRawTexture2DArray = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
if (compression === void 0) { compression = null; }
if (textureType === void 0) { textureType = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__["_DevTools"].WarnImport("Engine.RawTexture");
};
/** @hidden */
ThinEngine.prototype._unpackFlipY = function (value) {
if (this._unpackFlipYCached !== value) {
this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
if (this.enableUnpackFlipYCached) {
this._unpackFlipYCached = value;
}
}
};
/** @hidden */
ThinEngine.prototype._getUnpackAlignement = function () {
return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
};
ThinEngine.prototype._getTextureTarget = function (texture) {
if (texture.isCube) {
return this._gl.TEXTURE_CUBE_MAP;
}
else if (texture.is3D) {
return this._gl.TEXTURE_3D;
}
else if (texture.is2DArray || texture.isMultiview) {
return this._gl.TEXTURE_2D_ARRAY;
}
return this._gl.TEXTURE_2D;
};
/**
* Update the sampling mode of a given texture
* @param samplingMode defines the required sampling mode
* @param texture defines the texture to update
* @param generateMipMaps defines whether to generate mipmaps for the texture
*/
ThinEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture, generateMipMaps) {
if (generateMipMaps === void 0) { generateMipMaps = false; }
var target = this._getTextureTarget(texture);
var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps || generateMipMaps);
this._setTextureParameterInteger(target, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
this._setTextureParameterInteger(target, this._gl.TEXTURE_MIN_FILTER, filters.min);
if (generateMipMaps) {
texture.generateMipMaps = true;
this._gl.generateMipmap(target);
}
this._bindTextureDirectly(target, null);
texture.samplingMode = samplingMode;
};
/**
* Update the sampling mode of a given texture
* @param texture defines the texture to update
* @param wrapU defines the texture wrap mode of the u coordinates
* @param wrapV defines the texture wrap mode of the v coordinates
* @param wrapR defines the texture wrap mode of the r coordinates
*/
ThinEngine.prototype.updateTextureWrappingMode = function (texture, wrapU, wrapV, wrapR) {
if (wrapV === void 0) { wrapV = null; }
if (wrapR === void 0) { wrapR = null; }
var target = this._getTextureTarget(texture);
if (wrapU !== null) {
this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(wrapU), texture);
texture._cachedWrapU = wrapU;
}
if (wrapV !== null) {
this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(wrapV), texture);
texture._cachedWrapV = wrapV;
}
if ((texture.is2DArray || texture.is3D) && (wrapR !== null)) {
this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(wrapR), texture);
texture._cachedWrapR = wrapR;
}
this._bindTextureDirectly(target, null);
};
/** @hidden */
ThinEngine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
var width = size.width || size;
var height = size.height || size;
var layers = size.layers || 0;
internalTexture.baseWidth = width;
internalTexture.baseHeight = height;
internalTexture.width = width;
internalTexture.height = height;
internalTexture.is2DArray = layers > 0;
internalTexture.depth = layers;
internalTexture.isReady = true;
internalTexture.samples = 1;
internalTexture.generateMipMaps = false;
internalTexture._generateDepthBuffer = true;
internalTexture._generateStencilBuffer = generateStencil;
internalTexture.samplingMode = bilinearFiltering ? _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_BILINEAR_SAMPLINGMODE : _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE;
internalTexture.type = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT;
internalTexture._comparisonFunction = comparisonFunction;
var gl = this._gl;
var target = this._getTextureTarget(internalTexture);
var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
if (comparisonFunction === 0) {
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].LEQUAL);
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
}
else {
gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
}
};
/** @hidden */
ThinEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
var gl = this._gl;
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
};
/** @hidden */
ThinEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod, babylonInternalFormat, useTextureWidthAndHeight) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
if (useTextureWidthAndHeight === void 0) { useTextureWidthAndHeight = false; }
var gl = this._gl;
var textureType = this._getWebGLTextureType(texture.type);
var format = this._getInternalFormat(texture.format);
var internalFormat = babylonInternalFormat === undefined ? this._getRGBABufferInternalSizedFormat(texture.type, texture.format) : this._getInternalFormat(babylonInternalFormat);
this._unpackFlipY(texture.invertY);
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
var lodMaxWidth = Math.round(Math.log(texture.width) * Math.LOG2E);
var lodMaxHeight = Math.round(Math.log(texture.height) * Math.LOG2E);
var width = useTextureWidthAndHeight ? texture.width : Math.pow(2, Math.max(lodMaxWidth - lod, 0));
var height = useTextureWidthAndHeight ? texture.height : Math.pow(2, Math.max(lodMaxHeight - lod, 0));
gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
};
/**
* Update a portion of an internal texture
* @param texture defines the texture to update
* @param imageData defines the data to store into the texture
* @param xOffset defines the x coordinates of the update rectangle
* @param yOffset defines the y coordinates of the update rectangle
* @param width defines the width of the update rectangle
* @param height defines the height of the update rectangle
* @param faceIndex defines the face index if texture is a cube (0 by default)
* @param lod defines the lod level to update (0 by default)
*/
ThinEngine.prototype.updateTextureData = function (texture, imageData, xOffset, yOffset, width, height, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
var gl = this._gl;
var textureType = this._getWebGLTextureType(texture.type);
var format = this._getInternalFormat(texture.format);
this._unpackFlipY(texture.invertY);
var target = gl.TEXTURE_2D;
if (texture.isCube) {
target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
}
gl.texSubImage2D(target, lod, xOffset, yOffset, width, height, format, textureType, imageData);
};
/** @hidden */
ThinEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
if (faceIndex === void 0) { faceIndex = 0; }
if (lod === void 0) { lod = 0; }
var gl = this._gl;
var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
this._bindTextureDirectly(bindTarget, texture, true);
this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
this._bindTextureDirectly(bindTarget, null, true);
};
ThinEngine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
var gl = this._gl;
if (!gl) {
return;
}
var filters = this._getSamplingParameters(samplingMode, !noMipmap);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
if (!noMipmap && !isCompressed) {
gl.generateMipmap(gl.TEXTURE_2D);
}
this._bindTextureDirectly(gl.TEXTURE_2D, null);
// this.resetTextureCache();
if (scene) {
scene._removePendingData(texture);
}
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
};
ThinEngine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
var _this = this;
if (samplingMode === void 0) { samplingMode = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE; }
var maxTextureSize = this.getCaps().maxTextureSize;
var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(width, maxTextureSize) : width);
var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? ThinEngine.GetExponentOfTwo(height, maxTextureSize) : height);
var gl = this._gl;
if (!gl) {
return;
}
if (!texture._webGLTexture) {
// this.resetTextureCache();
if (scene) {
scene._removePendingData(texture);
}
return;
}
this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
texture.baseWidth = width;
texture.baseHeight = height;
texture.width = potWidth;
texture.height = potHeight;
texture.isReady = true;
if (processFunction(potWidth, potHeight, function () {
_this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
})) {
// Returning as texture needs extra async steps
return;
}
this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
};
/** @hidden */
ThinEngine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
if (samples === void 0) { samples = 1; }
var gl = this._gl;
// Create the depth/stencil buffer
if (generateStencilBuffer && generateDepthBuffer) {
return this._getDepthStencilBuffer(width, height, samples, gl.DEPTH_STENCIL, gl.DEPTH24_STENCIL8, gl.DEPTH_STENCIL_ATTACHMENT);
}
if (generateDepthBuffer) {
var depthFormat = gl.DEPTH_COMPONENT16;
if (this._webGLVersion > 1) {
depthFormat = gl.DEPTH_COMPONENT32F;
}
return this._getDepthStencilBuffer(width, height, samples, depthFormat, depthFormat, gl.DEPTH_ATTACHMENT);
}
if (generateStencilBuffer) {
return this._getDepthStencilBuffer(width, height, samples, gl.STENCIL_INDEX8, gl.STENCIL_INDEX8, gl.STENCIL_ATTACHMENT);
}
return null;
};
/** @hidden */
ThinEngine.prototype._releaseFramebufferObjects = function (texture) {
var gl = this._gl;
if (texture._framebuffer) {
gl.deleteFramebuffer(texture._framebuffer);
texture._framebuffer = null;
}
if (texture._depthStencilBuffer) {
gl.deleteRenderbuffer(texture._depthStencilBuffer);
texture._depthStencilBuffer = null;
}
if (texture._MSAAFramebuffer) {
gl.deleteFramebuffer(texture._MSAAFramebuffer);
texture._MSAAFramebuffer = null;
}
if (texture._MSAARenderBuffer) {
gl.deleteRenderbuffer(texture._MSAARenderBuffer);
texture._MSAARenderBuffer = null;
}
};
/** @hidden */
ThinEngine.prototype._releaseTexture = function (texture) {
this._releaseFramebufferObjects(texture);
this._deleteTexture(texture._webGLTexture);
// Unbind channels
this.unbindAllTextures();
var index = this._internalTexturesCache.indexOf(texture);
if (index !== -1) {
this._internalTexturesCache.splice(index, 1);
}
// Integrated fixed lod samplers.
if (texture._lodTextureHigh) {
texture._lodTextureHigh.dispose();
}
if (texture._lodTextureMid) {
texture._lodTextureMid.dispose();
}
if (texture._lodTextureLow) {
texture._lodTextureLow.dispose();
}
// Integrated irradiance map.
if (texture._irradianceTexture) {
texture._irradianceTexture.dispose();
}
};
ThinEngine.prototype._deleteTexture = function (texture) {
this._gl.deleteTexture(texture);
};
ThinEngine.prototype._setProgram = function (program) {
if (this._currentProgram !== program) {
this._gl.useProgram(program);
this._currentProgram = program;
}
};
/**
* Binds an effect to the webGL context
* @param effect defines the effect to bind
*/
ThinEngine.prototype.bindSamplers = function (effect) {
var webGLPipelineContext = effect.getPipelineContext();
this._setProgram(webGLPipelineContext.program);
var samplers = effect.getSamplers();
for (var index = 0; index < samplers.length; index++) {
var uniform = effect.getUniform(samplers[index]);
if (uniform) {
this._boundUniforms[index] = uniform;
}
}
this._currentEffect = null;
};
ThinEngine.prototype._activateCurrentTexture = function () {
if (this._currentTextureChannel !== this._activeChannel) {
this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
this._currentTextureChannel = this._activeChannel;
}
};
/** @hidden */
ThinEngine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
if (force === void 0) { force = false; }
var wasPreviouslyBound = false;
var isTextureForRendering = texture && texture._associatedChannel > -1;
if (forTextureDataUpdate && isTextureForRendering) {
this._activeChannel = texture._associatedChannel;
}
var currentTextureBound = this._boundTexturesCache[this._activeChannel];
if (currentTextureBound !== texture || force) {
this._activateCurrentTexture();
if (texture && texture.isMultiview) {
this._gl.bindTexture(target, texture ? texture._colorTextureArray : null);
}
else {
this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
}
this._boundTexturesCache[this._activeChannel] = texture;
if (texture) {
texture._associatedChannel = this._activeChannel;
}
}
else if (forTextureDataUpdate) {
wasPreviouslyBound = true;
this._activateCurrentTexture();
}
if (isTextureForRendering && !forTextureDataUpdate) {
this._bindSamplerUniformToChannel(texture._associatedChannel, this._activeChannel);
}
return wasPreviouslyBound;
};
/** @hidden */
ThinEngine.prototype._bindTexture = function (channel, texture) {
if (channel === undefined) {
return;
}
if (texture) {
texture._associatedChannel = channel;
}
this._activeChannel = channel;
var target = texture ? this._getTextureTarget(texture) : this._gl.TEXTURE_2D;
this._bindTextureDirectly(target, texture);
};
/**
* Unbind all textures from the webGL context
*/
ThinEngine.prototype.unbindAllTextures = function () {
for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
this._activeChannel = channel;
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
if (this.webGLVersion > 1) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
}
}
};
/**
* Sets a texture to the according uniform.
* @param channel The texture channel
* @param uniform The uniform to set
* @param texture The texture to apply
*/
ThinEngine.prototype.setTexture = function (channel, uniform, texture) {
if (channel === undefined) {
return;
}
if (uniform) {
this._boundUniforms[channel] = uniform;
}
this._setTexture(channel, texture);
};
ThinEngine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
var uniform = this._boundUniforms[sourceSlot];
if (!uniform || uniform._currentState === destination) {
return;
}
this._gl.uniform1i(uniform, destination);
uniform._currentState = destination;
};
ThinEngine.prototype._getTextureWrapMode = function (mode) {
switch (mode) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE:
return this._gl.REPEAT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_CLAMP_ADDRESSMODE:
return this._gl.CLAMP_TO_EDGE;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_MIRROR_ADDRESSMODE:
return this._gl.MIRRORED_REPEAT;
}
return this._gl.REPEAT;
};
ThinEngine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
if (depthStencilTexture === void 0) { depthStencilTexture = false; }
// Not ready?
if (!texture) {
if (this._boundTexturesCache[channel] != null) {
this._activeChannel = channel;
this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
if (this.webGLVersion > 1) {
this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
this._bindTextureDirectly(this._gl.TEXTURE_2D_ARRAY, null);
}
}
return false;
}
// Video
if (texture.video) {
this._activeChannel = channel;
texture.update();
}
else if (texture.delayLoadState === _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].DELAYLOADSTATE_NOTLOADED) { // Delay loading
texture.delayLoad();
return false;
}
var internalTexture;
if (depthStencilTexture) {
internalTexture = texture.depthStencilTexture;
}
else if (texture.isReady()) {
internalTexture = texture.getInternalTexture();
}
else if (texture.isCube) {
internalTexture = this.emptyCubeTexture;
}
else if (texture.is3D) {
internalTexture = this.emptyTexture3D;
}
else if (texture.is2DArray) {
internalTexture = this.emptyTexture2DArray;
}
else {
internalTexture = this.emptyTexture;
}
if (!isPartOfTextureArray && internalTexture) {
internalTexture._associatedChannel = channel;
}
var needToBind = true;
if (this._boundTexturesCache[channel] === internalTexture) {
if (!isPartOfTextureArray) {
this._bindSamplerUniformToChannel(internalTexture._associatedChannel, channel);
}
needToBind = false;
}
this._activeChannel = channel;
var target = this._getTextureTarget(internalTexture);
if (needToBind) {
this._bindTextureDirectly(target, internalTexture, isPartOfTextureArray);
}
if (internalTexture && !internalTexture.isMultiview) {
// CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
if (internalTexture.isCube && internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
var textureWrapMode = (texture.coordinatesMode !== _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_CUBIC_MODE && texture.coordinatesMode !== _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_SKYBOX_MODE) ? _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_WRAP_ADDRESSMODE : _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_CLAMP_ADDRESSMODE;
texture.wrapU = textureWrapMode;
texture.wrapV = textureWrapMode;
}
if (internalTexture._cachedWrapU !== texture.wrapU) {
internalTexture._cachedWrapU = texture.wrapU;
this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
}
if (internalTexture._cachedWrapV !== texture.wrapV) {
internalTexture._cachedWrapV = texture.wrapV;
this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
}
if (internalTexture.is3D && internalTexture._cachedWrapR !== texture.wrapR) {
internalTexture._cachedWrapR = texture.wrapR;
this._setTextureParameterInteger(target, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
}
this._setAnisotropicLevel(target, internalTexture, texture.anisotropicFilteringLevel);
}
return true;
};
/**
* Sets an array of texture to the webGL context
* @param channel defines the channel where the texture array must be set
* @param uniform defines the associated uniform location
* @param textures defines the array of textures to bind
*/
ThinEngine.prototype.setTextureArray = function (channel, uniform, textures) {
if (channel === undefined || !uniform) {
return;
}
if (!this._textureUnits || this._textureUnits.length !== textures.length) {
this._textureUnits = new Int32Array(textures.length);
}
for (var i = 0; i < textures.length; i++) {
var texture = textures[i].getInternalTexture();
if (texture) {
this._textureUnits[i] = channel + i;
texture._associatedChannel = channel + i;
}
else {
this._textureUnits[i] = -1;
}
}
this._gl.uniform1iv(uniform, this._textureUnits);
for (var index = 0; index < textures.length; index++) {
this._setTexture(this._textureUnits[index], textures[index], true);
}
};
/** @hidden */
ThinEngine.prototype._setAnisotropicLevel = function (target, internalTexture, anisotropicFilteringLevel) {
var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
if (internalTexture.samplingMode !== _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_LINEAR_MIPNEAREST
&& internalTexture.samplingMode !== _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_LINEAR_MIPLINEAR
&& internalTexture.samplingMode !== _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURE_LINEAR_LINEAR) {
anisotropicFilteringLevel = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
}
if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== anisotropicFilteringLevel) {
this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(anisotropicFilteringLevel, this._caps.maxAnisotropy), internalTexture);
internalTexture._cachedAnisotropicFilteringLevel = anisotropicFilteringLevel;
}
};
ThinEngine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
this._bindTextureDirectly(target, texture, true, true);
this._gl.texParameterf(target, parameter, value);
};
ThinEngine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
if (texture) {
this._bindTextureDirectly(target, texture, true, true);
}
this._gl.texParameteri(target, parameter, value);
};
/**
* Unbind all vertex attributes from the webGL context
*/
ThinEngine.prototype.unbindAllAttributes = function () {
if (this._mustWipeVertexAttributes) {
this._mustWipeVertexAttributes = false;
for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
this.disableAttributeByIndex(i);
}
return;
}
for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
continue;
}
this.disableAttributeByIndex(i);
}
};
/**
* Force the engine to release all cached effects. This means that next effect compilation will have to be done completely even if a similar effect was already compiled
*/
ThinEngine.prototype.releaseEffects = function () {
for (var name in this._compiledEffects) {
var webGLPipelineContext = this._compiledEffects[name].getPipelineContext();
this._deletePipelineContext(webGLPipelineContext);
}
this._compiledEffects = {};
};
/**
* Dispose and release all associated resources
*/
ThinEngine.prototype.dispose = function () {
this.stopRenderLoop();
// Clear observables
if (this.onBeforeTextureInitObservable) {
this.onBeforeTextureInitObservable.clear();
}
// Empty texture
if (this._emptyTexture) {
this._releaseTexture(this._emptyTexture);
this._emptyTexture = null;
}
if (this._emptyCubeTexture) {
this._releaseTexture(this._emptyCubeTexture);
this._emptyCubeTexture = null;
}
if (this._dummyFramebuffer) {
this._gl.deleteFramebuffer(this._dummyFramebuffer);
}
// Release effects
this.releaseEffects();
// Unbind
this.unbindAllAttributes();
this._boundUniforms = [];
// Events
if (_Misc_domManagement__WEBPACK_IMPORTED_MODULE_10__["DomManagement"].IsWindowObjectExist()) {
if (this._renderingCanvas) {
if (!this._doNotHandleContextLost) {
this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
}
}
}
this._workingCanvas = null;
this._workingContext = null;
this._currentBufferPointers = [];
this._renderingCanvas = null;
this._currentProgram = null;
this._boundRenderFunction = null;
_Materials_effect__WEBPACK_IMPORTED_MODULE_1__["Effect"].ResetCache();
// Abort active requests
for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
var request = _a[_i];
request.abort();
}
};
/**
* Attach a new callback raised when context lost event is fired
* @param callback defines the callback to call
*/
ThinEngine.prototype.attachContextLostEvent = function (callback) {
if (this._renderingCanvas) {
this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
}
};
/**
* Attach a new callback raised when context restored event is fired
* @param callback defines the callback to call
*/
ThinEngine.prototype.attachContextRestoredEvent = function (callback) {
if (this._renderingCanvas) {
this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
}
};
/**
* Get the current error code of the webGL context
* @returns the error code
* @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
*/
ThinEngine.prototype.getError = function () {
return this._gl.getError();
};
ThinEngine.prototype._canRenderToFloatFramebuffer = function () {
if (this._webGLVersion > 1) {
return this._caps.colorBufferFloat;
}
return this._canRenderToFramebuffer(_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT);
};
ThinEngine.prototype._canRenderToHalfFloatFramebuffer = function () {
if (this._webGLVersion > 1) {
return this._caps.colorBufferFloat;
}
return this._canRenderToFramebuffer(_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_HALF_FLOAT);
};
// Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
ThinEngine.prototype._canRenderToFramebuffer = function (type) {
var gl = this._gl;
//clear existing errors
while (gl.getError() !== gl.NO_ERROR) { }
var successful = true;
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
successful = successful && (gl.getError() === gl.NO_ERROR);
//try render by clearing frame buffer's color buffer
if (successful) {
gl.clear(gl.COLOR_BUFFER_BIT);
successful = successful && (gl.getError() === gl.NO_ERROR);
}
//try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
if (successful) {
//in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
var readFormat = gl.RGBA;
var readType = gl.UNSIGNED_BYTE;
var buffer = new Uint8Array(4);
gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
successful = successful && (gl.getError() === gl.NO_ERROR);
}
//clean up
gl.deleteTexture(texture);
gl.deleteFramebuffer(fb);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
//clear accumulated errors
while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
return successful;
};
/** @hidden */
ThinEngine.prototype._getWebGLTextureType = function (type) {
if (this._webGLVersion === 1) {
switch (type) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT:
return this._gl.FLOAT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_HALF_FLOAT:
return this._gl.HALF_FLOAT_OES;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_BYTE:
return this._gl.UNSIGNED_BYTE;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
return this._gl.UNSIGNED_SHORT_4_4_4_4;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
return this._gl.UNSIGNED_SHORT_5_5_5_1;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
return this._gl.UNSIGNED_SHORT_5_6_5;
}
return this._gl.UNSIGNED_BYTE;
}
switch (type) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_BYTE:
return this._gl.BYTE;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_BYTE:
return this._gl.UNSIGNED_BYTE;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_SHORT:
return this._gl.SHORT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT:
return this._gl.UNSIGNED_SHORT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_INT:
return this._gl.INT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
return this._gl.UNSIGNED_INT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT:
return this._gl.FLOAT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_HALF_FLOAT:
return this._gl.HALF_FLOAT;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
return this._gl.UNSIGNED_SHORT_4_4_4_4;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
return this._gl.UNSIGNED_SHORT_5_5_5_1;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
return this._gl.UNSIGNED_SHORT_5_6_5;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
return this._gl.UNSIGNED_INT_2_10_10_10_REV;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_24_8:
return this._gl.UNSIGNED_INT_24_8;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
return this._gl.UNSIGNED_INT_5_9_9_9_REV;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
}
return this._gl.UNSIGNED_BYTE;
};
/** @hidden */
ThinEngine.prototype._getInternalFormat = function (format) {
var internalFormat = this._gl.RGBA;
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_ALPHA:
internalFormat = this._gl.ALPHA;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_LUMINANCE:
internalFormat = this._gl.LUMINANCE;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA:
internalFormat = this._gl.LUMINANCE_ALPHA;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED:
internalFormat = this._gl.RED;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG:
internalFormat = this._gl.RG;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB:
internalFormat = this._gl.RGB;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA:
internalFormat = this._gl.RGBA;
break;
}
if (this._webGLVersion > 1) {
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
internalFormat = this._gl.RED_INTEGER;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
internalFormat = this._gl.RG_INTEGER;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
internalFormat = this._gl.RGB_INTEGER;
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
internalFormat = this._gl.RGBA_INTEGER;
break;
}
}
return internalFormat;
};
/** @hidden */
ThinEngine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
if (this._webGLVersion === 1) {
if (format !== undefined) {
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_ALPHA:
return this._gl.ALPHA;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_LUMINANCE:
return this._gl.LUMINANCE;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA:
return this._gl.LUMINANCE_ALPHA;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB:
return this._gl.RGB;
}
}
return this._gl.RGBA;
}
switch (type) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_BYTE:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED:
return this._gl.R8_SNORM;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG:
return this._gl.RG8_SNORM;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB:
return this._gl.RGB8_SNORM;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
return this._gl.R8I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG8I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB8I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA8I;
default:
return this._gl.RGBA8_SNORM;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_BYTE:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED:
return this._gl.R8;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG:
return this._gl.RG8;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB:
return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA:
return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
return this._gl.R8UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG8UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB8UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA8UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_ALPHA:
return this._gl.ALPHA;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_LUMINANCE:
return this._gl.LUMINANCE;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_LUMINANCE_ALPHA:
return this._gl.LUMINANCE_ALPHA;
default:
return this._gl.RGBA8;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_SHORT:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
return this._gl.R16I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG16I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB16I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA16I;
default:
return this._gl.RGBA16I;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
return this._gl.R16UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG16UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB16UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA16UI;
default:
return this._gl.RGBA16UI;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_INT:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
return this._gl.R32I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG32I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB32I;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA32I;
default:
return this._gl.RGBA32I;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED_INTEGER:
return this._gl.R32UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG_INTEGER:
return this._gl.RG32UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB_INTEGER:
return this._gl.RGB32UI;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGBA32UI;
default:
return this._gl.RGBA32UI;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED:
return this._gl.R32F; // By default. Other possibility is R16F.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG:
return this._gl.RG32F; // By default. Other possibility is RG16F.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB:
return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA:
return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
default:
return this._gl.RGBA32F;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_HALF_FLOAT:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RED:
return this._gl.R16F;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RG:
return this._gl.RG16F;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGB:
return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA:
return this._gl.RGBA16F;
default:
return this._gl.RGBA16F;
}
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
return this._gl.RGB565;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
return this._gl.R11F_G11F_B10F;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
return this._gl.RGB9_E5;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
return this._gl.RGBA4;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
return this._gl.RGB5_A1;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
switch (format) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA:
return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTUREFORMAT_RGBA_INTEGER:
return this._gl.RGB10_A2UI;
default:
return this._gl.RGB10_A2;
}
}
return this._gl.RGBA8;
};
/** @hidden */
ThinEngine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
if (type === _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_FLOAT) {
return this._gl.RGBA32F;
}
else if (type === _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].TEXTURETYPE_HALF_FLOAT) {
return this._gl.RGBA16F;
}
return this._gl.RGBA8;
};
/** @hidden */
ThinEngine.prototype._loadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
var _this = this;
var request = ThinEngine._FileToolsLoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
this._activeRequests.push(request);
request.onCompleteObservable.add(function (request) {
_this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
});
return request;
};
/**
* Loads a file from a url
* @param url url to load
* @param onSuccess callback called when the file successfully loads
* @param onProgress callback called while file is loading (if the server supports this mode)
* @param offlineProvider defines the offline provider for caching
* @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
* @param onError callback called when the file fails to load
* @returns a file request object
* @hidden
*/
ThinEngine._FileToolsLoadFile = function (url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_2__["_DevTools"].WarnImport("FileTools");
};
/**
* Reads pixels from the current frame buffer. Please note that this function can be slow
* @param x defines the x coordinate of the rectangle where pixels must be read
* @param y defines the y coordinate of the rectangle where pixels must be read
* @param width defines the width of the rectangle where pixels must be read
* @param height defines the height of the rectangle where pixels must be read
* @param hasAlpha defines whether the output should have alpha or not (defaults to true)
* @returns a Uint8Array containing RGBA colors
*/
ThinEngine.prototype.readPixels = function (x, y, width, height, hasAlpha) {
if (hasAlpha === void 0) { hasAlpha = true; }
var numChannels = hasAlpha ? 4 : 3;
var format = hasAlpha ? this._gl.RGBA : this._gl.RGB;
var data = new Uint8Array(height * width * numChannels);
this._gl.readPixels(x, y, width, height, format, this._gl.UNSIGNED_BYTE, data);
return data;
};
/**
* Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
* @returns true if the engine can be created
* @ignorenaming
*/
ThinEngine.isSupported = function () {
if (this._isSupported === null) {
try {
var tempcanvas = _Misc_canvasGenerator__WEBPACK_IMPORTED_MODULE_14__["CanvasGenerator"].CreateCanvas(1, 1);
var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
this._isSupported = gl != null && !!window.WebGLRenderingContext;
}
catch (e) {
this._isSupported = false;
}
}
return this._isSupported;
};
/**
* Find the next highest power of two.
* @param x Number to start search from.
* @return Next highest power of two.
*/
ThinEngine.CeilingPOT = function (x) {
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
};
/**
* Find the next lowest power of two.
* @param x Number to start search from.
* @return Next lowest power of two.
*/
ThinEngine.FloorPOT = function (x) {
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >> 16);
return x - (x >> 1);
};
/**
* Find the nearest power of two.
* @param x Number to start search from.
* @return Next nearest power of two.
*/
ThinEngine.NearestPOT = function (x) {
var c = ThinEngine.CeilingPOT(x);
var f = ThinEngine.FloorPOT(x);
return (c - x) > (x - f) ? f : c;
};
/**
* Get the closest exponent of two
* @param value defines the value to approximate
* @param max defines the maximum value to return
* @param mode defines how to define the closest value
* @returns closest exponent of two of the given value
*/
ThinEngine.GetExponentOfTwo = function (value, max, mode) {
if (mode === void 0) { mode = _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCALEMODE_NEAREST; }
var pot;
switch (mode) {
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCALEMODE_FLOOR:
pot = ThinEngine.FloorPOT(value);
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCALEMODE_NEAREST:
pot = ThinEngine.NearestPOT(value);
break;
case _constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCALEMODE_CEILING:
default:
pot = ThinEngine.CeilingPOT(value);
break;
}
return Math.min(pot, max);
};
/**
* Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
* @param func - the function to be called
* @param requester - the object that will request the next frame. Falls back to window.
* @returns frame number
*/
ThinEngine.QueueNewFrame = function (func, requester) {
if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_10__["DomManagement"].IsWindowObjectExist()) {
if (typeof requestAnimationFrame !== "undefined") {
return requestAnimationFrame(func);
}
return setTimeout(func, 16);
}
if (!requester) {
requester = window;
}
if (requester.requestPostAnimationFrame) {
return requester.requestPostAnimationFrame(func);
}
else if (requester.requestAnimationFrame) {
return requester.requestAnimationFrame(func);
}
else if (requester.msRequestAnimationFrame) {
return requester.msRequestAnimationFrame(func);
}
else if (requester.webkitRequestAnimationFrame) {
return requester.webkitRequestAnimationFrame(func);
}
else if (requester.mozRequestAnimationFrame) {
return requester.mozRequestAnimationFrame(func);
}
else if (requester.oRequestAnimationFrame) {
return requester.oRequestAnimationFrame(func);
}
else {
return window.setTimeout(func, 16);
}
};
/**
* Gets host document
* @returns the host document object
*/
ThinEngine.prototype.getHostDocument = function () {
if (this._renderingCanvas && this._renderingCanvas.ownerDocument) {
return this._renderingCanvas.ownerDocument;
}
return document;
};
/** Use this array to turn off some WebGL2 features on known buggy browsers version */
ThinEngine.ExceptionList = [
{ key: "Chrome\/63\.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
{ key: "Firefox\/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Firefox\/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
{ key: "Chrome\/72.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Chrome\/73.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Chrome\/74.+?Mobile", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Mac OS.+Chrome\/71", capture: null, captureConstraint: null, targets: ["vao"] },
{ key: "Mac OS.+Chrome\/72", capture: null, captureConstraint: null, targets: ["vao"] }
];
/** @hidden */
ThinEngine._TextureLoaders = [];
// Updatable statics so stick with vars here
/**
* Gets or sets the epsilon value used by collision engine
*/
ThinEngine.CollisionsEpsilon = 0.001;
// Statics
ThinEngine._isSupported = null;
return ThinEngine;
}());
/***/ }),
/***/ "./Events/clipboardEvents.ts":
/*!***********************************!*\
!*** ./Events/clipboardEvents.ts ***!
\***********************************/
/*! exports provided: ClipboardEventTypes, ClipboardInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return ClipboardEventTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return ClipboardInfo; });
/**
* Gather the list of clipboard event types as constants.
*/
var ClipboardEventTypes = /** @class */ (function () {
function ClipboardEventTypes() {
}
/**
* The clipboard event is fired when a copy command is active (pressed).
*/
ClipboardEventTypes.COPY = 0x01; //
/**
* The clipboard event is fired when a cut command is active (pressed).
*/
ClipboardEventTypes.CUT = 0x02;
/**
* The clipboard event is fired when a paste command is active (pressed).
*/
ClipboardEventTypes.PASTE = 0x03;
return ClipboardEventTypes;
}());
/**
* This class is used to store clipboard related info for the onClipboardObservable event.
*/
var ClipboardInfo = /** @class */ (function () {
/**
*Creates an instance of ClipboardInfo.
* @param type Defines the type of event (BABYLON.ClipboardEventTypes)
* @param event Defines the related dom event
*/
function ClipboardInfo(
/**
* Defines the type of event (BABYLON.ClipboardEventTypes)
*/
type,
/**
* Defines the related dom event
*/
event) {
this.type = type;
this.event = event;
}
/**
* Get the clipboard event's type from the keycode.
* @param keyCode Defines the keyCode for the current keyboard event.
* @return {number}
*/
ClipboardInfo.GetTypeFromCharacter = function (keyCode) {
var charCode = keyCode;
//TODO: add codes for extended ASCII
switch (charCode) {
case 67: return ClipboardEventTypes.COPY;
case 86: return ClipboardEventTypes.PASTE;
case 88: return ClipboardEventTypes.CUT;
default: return -1;
}
};
return ClipboardInfo;
}());
/***/ }),
/***/ "./Events/index.ts":
/*!*************************!*\
!*** ./Events/index.ts ***!
\*************************/
/*! exports provided: KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo, ClipboardEventTypes, ClipboardInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./keyboardEvents */ "./Events/keyboardEvents.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardEventTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return _keyboardEvents__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfoPre"]; });
/* harmony import */ var _pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pointerEvents */ "./Events/pointerEvents.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfoBase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfoPre"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return _pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerInfo"]; });
/* harmony import */ var _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./clipboardEvents */ "./Events/clipboardEvents.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__["ClipboardEventTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return _clipboardEvents__WEBPACK_IMPORTED_MODULE_2__["ClipboardInfo"]; });
/***/ }),
/***/ "./Events/keyboardEvents.ts":
/*!**********************************!*\
!*** ./Events/keyboardEvents.ts ***!
\**********************************/
/*! exports provided: KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return KeyboardEventTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return KeyboardInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return KeyboardInfoPre; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/**
* Gather the list of keyboard event types as constants.
*/
var KeyboardEventTypes = /** @class */ (function () {
function KeyboardEventTypes() {
}
/**
* The keydown event is fired when a key becomes active (pressed).
*/
KeyboardEventTypes.KEYDOWN = 0x01;
/**
* The keyup event is fired when a key has been released.
*/
KeyboardEventTypes.KEYUP = 0x02;
return KeyboardEventTypes;
}());
/**
* This class is used to store keyboard related info for the onKeyboardObservable event.
*/
var KeyboardInfo = /** @class */ (function () {
/**
* Instantiates a new keyboard info.
* This class is used to store keyboard related info for the onKeyboardObservable event.
* @param type Defines the type of event (KeyboardEventTypes)
* @param event Defines the related dom event
*/
function KeyboardInfo(
/**
* Defines the type of event (KeyboardEventTypes)
*/
type,
/**
* Defines the related dom event
*/
event) {
this.type = type;
this.event = event;
}
return KeyboardInfo;
}());
/**
* This class is used to store keyboard related info for the onPreKeyboardObservable event.
* Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
*/
var KeyboardInfoPre = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(KeyboardInfoPre, _super);
/**
* Instantiates a new keyboard pre info.
* This class is used to store keyboard related info for the onPreKeyboardObservable event.
* @param type Defines the type of event (KeyboardEventTypes)
* @param event Defines the related dom event
*/
function KeyboardInfoPre(
/**
* Defines the type of event (KeyboardEventTypes)
*/
type,
/**
* Defines the related dom event
*/
event) {
var _this = _super.call(this, type, event) || this;
_this.type = type;
_this.event = event;
_this.skipOnPointerObservable = false;
return _this;
}
return KeyboardInfoPre;
}(KeyboardInfo));
/***/ }),
/***/ "./Events/pointerEvents.ts":
/*!*********************************!*\
!*** ./Events/pointerEvents.ts ***!
\*********************************/
/*! exports provided: PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return PointerEventTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return PointerInfoBase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return PointerInfoPre; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return PointerInfo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/**
* Gather the list of pointer event types as constants.
*/
var PointerEventTypes = /** @class */ (function () {
function PointerEventTypes() {
}
/**
* The pointerdown event is fired when a pointer becomes active. For mouse, it is fired when the device transitions from no buttons depressed to at least one button depressed. For touch, it is fired when physical contact is made with the digitizer. For pen, it is fired when the stylus makes physical contact with the digitizer.
*/
PointerEventTypes.POINTERDOWN = 0x01;
/**
* The pointerup event is fired when a pointer is no longer active.
*/
PointerEventTypes.POINTERUP = 0x02;
/**
* The pointermove event is fired when a pointer changes coordinates.
*/
PointerEventTypes.POINTERMOVE = 0x04;
/**
* The pointerwheel event is fired when a mouse wheel has been rotated.
*/
PointerEventTypes.POINTERWHEEL = 0x08;
/**
* The pointerpick event is fired when a mesh or sprite has been picked by the pointer.
*/
PointerEventTypes.POINTERPICK = 0x10;
/**
* The pointertap event is fired when a the object has been touched and released without drag.
*/
PointerEventTypes.POINTERTAP = 0x20;
/**
* The pointerdoubletap event is fired when a the object has been touched and released twice without drag.
*/
PointerEventTypes.POINTERDOUBLETAP = 0x40;
return PointerEventTypes;
}());
/**
* Base class of pointer info types.
*/
var PointerInfoBase = /** @class */ (function () {
/**
* Instantiates the base class of pointers info.
* @param type Defines the type of event (PointerEventTypes)
* @param event Defines the related dom event
*/
function PointerInfoBase(
/**
* Defines the type of event (PointerEventTypes)
*/
type,
/**
* Defines the related dom event
*/
event) {
this.type = type;
this.event = event;
}
return PointerInfoBase;
}());
/**
* This class is used to store pointer related info for the onPrePointerObservable event.
* Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
*/
var PointerInfoPre = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PointerInfoPre, _super);
/**
* Instantiates a PointerInfoPre to store pointer related info to the onPrePointerObservable event.
* @param type Defines the type of event (PointerEventTypes)
* @param event Defines the related dom event
* @param localX Defines the local x coordinates of the pointer when the event occured
* @param localY Defines the local y coordinates of the pointer when the event occured
*/
function PointerInfoPre(type, event, localX, localY) {
var _this = _super.call(this, type, event) || this;
/**
* Ray from a pointer if availible (eg. 6dof controller)
*/
_this.ray = null;
_this.skipOnPointerObservable = false;
_this.localPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector2"](localX, localY);
return _this;
}
return PointerInfoPre;
}(PointerInfoBase));
/**
* This type contains all the data related to a pointer event in Babylon.js.
* The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
*/
var PointerInfo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PointerInfo, _super);
/**
* Instantiates a PointerInfo to store pointer related info to the onPointerObservable event.
* @param type Defines the type of event (PointerEventTypes)
* @param event Defines the related dom event
* @param pickInfo Defines the picking info associated to the info (if any)\
*/
function PointerInfo(type, event,
/**
* Defines the picking info associated to the info (if any)\
*/
pickInfo) {
var _this = _super.call(this, type, event) || this;
_this.pickInfo = pickInfo;
return _this;
}
return PointerInfo;
}(PointerInfoBase));
/***/ }),
/***/ "./Gamepads/Controllers/daydreamController.ts":
/*!****************************************************!*\
!*** ./Gamepads/Controllers/daydreamController.ts ***!
\****************************************************/
/*! exports provided: DaydreamController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return DaydreamController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/**
* Google Daydream controller
*/
var DaydreamController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DaydreamController, _super);
/**
* Creates a new DaydreamController from a gamepad
* @param vrGamepad the gamepad that the controller should be created from
*/
function DaydreamController(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"].DAYDREAM;
return _this;
}
/**
* Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
* @param scene scene in which to add meshes
* @param meshLoaded optional callback function that will be called if the mesh loads successfully.
*/
DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
var _this = this;
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"].ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
/**
* Called once for each button that changed state since the last frame
* @param buttonIdx Which button index changed
* @param state New state of the button
* @param changes Which properties on the state changed since last frame
*/
DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
// Daydream controller only has 1 GamepadButton (on the trackpad).
if (buttonIdx === 0) {
var observable = this.onTriggerStateChangedObservable;
if (observable) {
observable.notifyObservers(state);
}
}
else {
// If the app or home buttons are ever made available
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Unrecognized Daydream button index: " + buttonIdx);
}
};
/**
* Base Url for the controller model.
*/
DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
/**
* File name for the controller model.
*/
DaydreamController.MODEL_FILENAME = 'generic.babylon';
/**
* Gamepad Id prefix used to identify Daydream Controller.
*/
DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
return DaydreamController;
}(_webVRController__WEBPACK_IMPORTED_MODULE_3__["WebVRController"]));
_poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]._ControllerFactories.push({
canCreate: function (gamepadInfo) {
return gamepadInfo.id.indexOf(DaydreamController.GAMEPAD_ID_PREFIX) === 0;
},
create: function (gamepadInfo) {
return new DaydreamController(gamepadInfo);
}
});
/***/ }),
/***/ "./Gamepads/Controllers/gearVRController.ts":
/*!**************************************************!*\
!*** ./Gamepads/Controllers/gearVRController.ts ***!
\**************************************************/
/*! exports provided: GearVRController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return GearVRController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/**
* Gear VR Controller
*/
var GearVRController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GearVRController, _super);
/**
* Creates a new GearVRController from a gamepad
* @param vrGamepad the gamepad that the controller should be created from
*/
function GearVRController(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this._buttonIndexToObservableNameMap = [
'onPadStateChangedObservable',
'onTriggerStateChangedObservable' // Trigger
];
_this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_5__["PoseEnabledControllerType"].GEAR_VR;
// Initial starting position defaults to where hand would be (incase of only 3dof controller)
_this._calculatedPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
_this._disableTrackPosition(_this._calculatedPosition);
return _this;
}
/**
* Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
* @param scene scene in which to add meshes
* @param meshLoaded optional callback function that will be called if the mesh loads successfully.
*/
GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
var _this = this;
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_3__["SceneLoader"].ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
// Offset the controller so it will rotate around the users wrist
var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"]("", scene);
newMeshes[1].parent = mesh;
newMeshes[1].position.z = -0.15;
_this._defaultModel = mesh;
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
/**
* Called once for each button that changed state since the last frame
* @param buttonIdx Which button index changed
* @param state New state of the button
* @param changes Which properties on the state changed since last frame
*/
GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
// Only emit events for buttons that we know how to map from index to observable
var observable = this[observableName];
if (observable) {
observable.notifyObservers(state);
}
}
};
/**
* Base Url for the controller model.
*/
GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
/**
* File name for the controller model.
*/
GearVRController.MODEL_FILENAME = 'generic.babylon';
/**
* Gamepad Id prefix used to identify this controller.
*/
GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
return GearVRController;
}(_webVRController__WEBPACK_IMPORTED_MODULE_4__["WebVRController"]));
_poseEnabledController__WEBPACK_IMPORTED_MODULE_5__["PoseEnabledControllerHelper"]._ControllerFactories.push({
canCreate: function (gamepadInfo) {
return gamepadInfo.id.indexOf(GearVRController.GAMEPAD_ID_PREFIX) === 0 ||
gamepadInfo.id.indexOf('Oculus Go') !== -1 ||
gamepadInfo.id.indexOf('Vive Focus') !== -1;
},
create: function (gamepadInfo) {
return new GearVRController(gamepadInfo);
}
});
/***/ }),
/***/ "./Gamepads/Controllers/genericController.ts":
/*!***************************************************!*\
!*** ./Gamepads/Controllers/genericController.ts ***!
\***************************************************/
/*! exports provided: GenericController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return GenericController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/**
* Generic Controller
*/
var GenericController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GenericController, _super);
/**
* Creates a new GenericController from a gamepad
* @param vrGamepad the gamepad that the controller should be created from
*/
function GenericController(vrGamepad) {
return _super.call(this, vrGamepad) || this;
}
/**
* Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
* @param scene scene in which to add meshes
* @param meshLoaded optional callback function that will be called if the mesh loads successfully.
*/
GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
var _this = this;
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__["SceneLoader"].ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
/**
* Called once for each button that changed state since the last frame
* @param buttonIdx Which button index changed
* @param state New state of the button
* @param changes Which properties on the state changed since last frame
*/
GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
console.log("Button id: " + buttonIdx + "state: ");
console.dir(state);
};
/**
* Base Url for the controller model.
*/
GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
/**
* File name for the controller model.
*/
GenericController.MODEL_FILENAME = 'generic.babylon';
return GenericController;
}(_webVRController__WEBPACK_IMPORTED_MODULE_2__["WebVRController"]));
_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"]._DefaultControllerFactory = function (gamepadInfo) { return new GenericController(gamepadInfo); };
/***/ }),
/***/ "./Gamepads/Controllers/index.ts":
/*!***************************************!*\
!*** ./Gamepads/Controllers/index.ts ***!
\***************************************/
/*! exports provided: DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController, XRWindowsMotionController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _daydreamController__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./daydreamController */ "./Gamepads/Controllers/daydreamController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _daydreamController__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; });
/* harmony import */ var _gearVRController__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gearVRController */ "./Gamepads/Controllers/gearVRController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _gearVRController__WEBPACK_IMPORTED_MODULE_1__["GearVRController"]; });
/* harmony import */ var _genericController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./genericController */ "./Gamepads/Controllers/genericController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _genericController__WEBPACK_IMPORTED_MODULE_2__["GenericController"]; });
/* harmony import */ var _oculusTouchController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./oculusTouchController */ "./Gamepads/Controllers/oculusTouchController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _oculusTouchController__WEBPACK_IMPORTED_MODULE_3__["OculusTouchController"]; });
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledController"]; });
/* harmony import */ var _viveController__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./viveController */ "./Gamepads/Controllers/viveController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _viveController__WEBPACK_IMPORTED_MODULE_5__["ViveController"]; });
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _webVRController__WEBPACK_IMPORTED_MODULE_6__["WebVRController"]; });
/* harmony import */ var _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./windowsMotionController */ "./Gamepads/Controllers/windowsMotionController.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__["WindowsMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "XRWindowsMotionController", function() { return _windowsMotionController__WEBPACK_IMPORTED_MODULE_7__["XRWindowsMotionController"]; });
/***/ }),
/***/ "./Gamepads/Controllers/oculusTouchController.ts":
/*!*******************************************************!*\
!*** ./Gamepads/Controllers/oculusTouchController.ts ***!
\*******************************************************/
/*! exports provided: OculusTouchController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return OculusTouchController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts");
/**
* Oculus Touch Controller
*/
var OculusTouchController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(OculusTouchController, _super);
/**
* Creates a new OculusTouchController from a gamepad
* @param vrGamepad the gamepad that the controller should be created from
*/
function OculusTouchController(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
/**
* Fired when the secondary trigger on this controller is modified
*/
_this.onSecondaryTriggerStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when the thumb rest on this controller is modified
*/
_this.onThumbRestChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerType"].OCULUS;
return _this;
}
/**
* Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
* @param scene scene in which to add meshes
* @param meshLoaded optional callback function that will be called if the mesh loads successfully.
*/
OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
var _this = this;
var meshName;
// Hand
if (this.hand === 'left') {
meshName = OculusTouchController.MODEL_LEFT_FILENAME;
}
else { // Right is the default if no hand is specified
meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
}
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"].ImportMesh("", OculusTouchController._IsQuest ? OculusTouchController.QUEST_MODEL_BASE_URL : OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
/*
Parent Mesh name: oculus_touch_left
- body
- trigger
- thumbstick
- grip
- button_y
- button_x
- button_enter
*/
_this._defaultModel = OculusTouchController._IsQuest ? newMeshes[0] : newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
/**
* Fired when the A button on this controller is modified
*/
get: function () {
if (this.hand === 'right') {
return this.onMainButtonStateChangedObservable;
}
else {
throw new Error('No A button on left hand');
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
/**
* Fired when the B button on this controller is modified
*/
get: function () {
if (this.hand === 'right') {
return this.onSecondaryButtonStateChangedObservable;
}
else {
throw new Error('No B button on left hand');
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
/**
* Fired when the X button on this controller is modified
*/
get: function () {
if (this.hand === 'left') {
return this.onMainButtonStateChangedObservable;
}
else {
throw new Error('No X button on right hand');
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
/**
* Fired when the Y button on this controller is modified
*/
get: function () {
if (this.hand === 'left') {
return this.onSecondaryButtonStateChangedObservable;
}
else {
throw new Error('No Y button on right hand');
}
},
enumerable: false,
configurable: true
});
/**
* Called once for each button that changed state since the last frame
* 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
* 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
* 2) secondary trigger (same)
* 3) A (right) X (left), touch, pressed = value
* 4) B / Y
* 5) thumb rest
* @param buttonIdx Which button index changed
* @param state New state of the button
* @param changes Which properties on the state changed since last frame
*/
OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
var notifyObject = state; //{ state: state, changes: changes };
var triggerDirection = this.hand === 'right' ? -1 : 1;
switch (buttonIdx) {
case 0:
this.onPadStateChangedObservable.notifyObservers(notifyObject);
return;
case 1: // index trigger
if (!OculusTouchController._IsQuest && this._defaultModel) {
(this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
(this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
(this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
}
this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
return;
case 2: // secondary trigger
if (!OculusTouchController._IsQuest && this._defaultModel) {
(this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
}
this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
return;
case 3:
if (!OculusTouchController._IsQuest && this._defaultModel) {
if (notifyObject.pressed) {
(this._defaultModel.getChildren()[1]).position.y = -0.001;
}
else {
(this._defaultModel.getChildren()[1]).position.y = 0;
}
}
this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
return;
case 4:
if (!OculusTouchController._IsQuest && this._defaultModel) {
if (notifyObject.pressed) {
(this._defaultModel.getChildren()[2]).position.y = -0.001;
}
else {
(this._defaultModel.getChildren()[2]).position.y = 0;
}
}
this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
return;
case 5:
this.onThumbRestChangedObservable.notifyObservers(notifyObject);
return;
}
};
/**
* Base Url for the controller model.
*/
OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
/**
* File name for the left controller model.
*/
OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
/**
* File name for the right controller model.
*/
OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
/**
* Base Url for the Quest controller model.
*/
OculusTouchController.QUEST_MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculusQuest/';
/**
* @hidden
* If the controllers are running on a device that needs the updated Quest controller models
*/
OculusTouchController._IsQuest = false;
return OculusTouchController;
}(_webVRController__WEBPACK_IMPORTED_MODULE_3__["WebVRController"]));
_poseEnabledController__WEBPACK_IMPORTED_MODULE_4__["PoseEnabledControllerHelper"]._ControllerFactories.push({
canCreate: function (gamepadInfo) {
// If the headset reports being an Oculus Quest, use the Quest controller models
if (_Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].LastCreatedEngine && _Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].LastCreatedEngine._vrDisplay && _Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].LastCreatedEngine._vrDisplay.displayName === "Oculus Quest") {
OculusTouchController._IsQuest = true;
}
return gamepadInfo.id.indexOf('Oculus Touch') !== -1;
},
create: function (gamepadInfo) {
return new OculusTouchController(gamepadInfo);
}
});
/***/ }),
/***/ "./Gamepads/Controllers/poseEnabledController.ts":
/*!*******************************************************!*\
!*** ./Gamepads/Controllers/poseEnabledController.ts ***!
\*******************************************************/
/*! exports provided: PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return PoseEnabledControllerType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return PoseEnabledControllerHelper; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return PoseEnabledController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Engines/engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Gamepads/gamepad */ "./Gamepads/gamepad.ts");
/**
* Defines the types of pose enabled controllers that are supported
*/
var PoseEnabledControllerType;
(function (PoseEnabledControllerType) {
/**
* HTC Vive
*/
PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
/**
* Oculus Rift
*/
PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
/**
* Windows mixed reality
*/
PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
/**
* Samsung gear VR
*/
PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
/**
* Google Daydream
*/
PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
/**
* Generic
*/
PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
})(PoseEnabledControllerType || (PoseEnabledControllerType = {}));
/**
* Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
*/
var PoseEnabledControllerHelper = /** @class */ (function () {
function PoseEnabledControllerHelper() {
}
/**
* Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
* @param vrGamepad the gamepad to initialized
* @returns a vr controller of the type the gamepad identified as
*/
PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
for (var _i = 0, _a = this._ControllerFactories; _i < _a.length; _i++) {
var factory = _a[_i];
if (factory.canCreate(vrGamepad)) {
return factory.create(vrGamepad);
}
}
if (this._DefaultControllerFactory) {
return this._DefaultControllerFactory(vrGamepad);
}
throw "The type of gamepad you are trying to load needs to be imported first or is not supported.";
};
/** @hidden */
PoseEnabledControllerHelper._ControllerFactories = [];
/** @hidden */
PoseEnabledControllerHelper._DefaultControllerFactory = null;
return PoseEnabledControllerHelper;
}());
/**
* Defines the PoseEnabledController object that contains state of a vr capable controller
*/
var PoseEnabledController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PoseEnabledController, _super);
/**
* Creates a new PoseEnabledController from a gamepad
* @param browserGamepad the gamepad that the PoseEnabledController should be created from
*/
function PoseEnabledController(browserGamepad) {
var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
/**
* If the controller is used in a webXR session
*/
_this.isXR = false;
// Represents device position and rotation in room space. Should only be used to help calculate babylon space values
_this._deviceRoomPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._deviceRoomRotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
/**
* The device position in babylon space
*/
_this.devicePosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
/**
* The device rotation in babylon space
*/
_this.deviceRotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
/**
* The scale factor of the device in babylon space
*/
_this.deviceScaleFactor = 1;
// Used to convert 6dof controllers to 3dof
_this._trackPosition = true;
_this._maxRotationDistFromHeadset = Math.PI / 5;
_this._draggedRoomRotation = 0;
_this._leftHandSystemQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
/**
* Internal, matrix used to convert room space to babylon space
* @hidden
*/
_this._deviceToWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity();
/**
* Node to be used when casting a ray from the controller
* @hidden
*/
_this._pointingPoseNode = null;
_this._workingMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity();
/**
* @hidden
*/
_this._meshAttachedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.type = _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"].POSE_ENABLED;
_this.controllerType = PoseEnabledControllerType.GENERIC;
_this.position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
_this._calculatedPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._calculatedRotation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
return _this;
}
/**
* @hidden
*/
PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
if (this._trackPosition) {
this._calculatedPosition.copyFrom(fixedPosition);
this._trackPosition = false;
}
};
/**
* Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
*/
PoseEnabledController.prototype.update = function () {
_super.prototype.update.call(this);
this._updatePoseAndMesh();
};
/**
* Updates only the pose device and mesh without doing any button event checking
*/
PoseEnabledController.prototype._updatePoseAndMesh = function () {
if (this.isXR) {
return;
}
var pose = this.browserGamepad.pose;
this.updateFromDevice(pose);
if (!this._trackPosition && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera && _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera.devicePosition) {
var camera = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_4__["EngineStore"].LastCreatedScene.activeCamera;
camera._computeDevicePosition();
this._deviceToWorld.setTranslation(camera.devicePosition);
if (camera.deviceRotationQuaternion) {
var camera = camera;
camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Vector3[0]);
// Find the radian distance away that the headset is from the controllers rotation
var distanceAway = Math.atan2(Math.sin(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Vector3[0].y - this._draggedRoomRotation), Math.cos(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["TmpVectors"].Vector3[0].y - this._draggedRoomRotation));
if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
// Only rotate enouph to be within the _maxRotationDistFromHeadset
var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
this._draggedRoomRotation += rotationAmount;
// Rotate controller around headset
var sin = Math.sin(-rotationAmount);
var cos = Math.cos(-rotationAmount);
this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
}
}
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
if (this._mesh) {
this._mesh.position.copyFrom(this.devicePosition);
if (this._mesh.rotationQuaternion) {
this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
}
}
};
/**
* Updates the state of the pose enbaled controller based on the raw pose data from the device
* @param poseData raw pose fromthe device
*/
PoseEnabledController.prototype.updateFromDevice = function (poseData) {
if (this.isXR) {
return;
}
if (poseData) {
this.rawPose = poseData;
if (poseData.position) {
this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
this._deviceRoomPosition.z *= -1;
}
if (this._trackPosition) {
this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
}
this._calculatedPosition.addInPlace(this.position);
}
var pose = this.rawPose;
if (poseData.orientation && pose.orientation && pose.orientation.length === 4) {
this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
if (this._mesh) {
if (this._mesh.getScene().useRightHandedSystem) {
this._deviceRoomRotationQuaternion.z *= -1;
this._deviceRoomRotationQuaternion.w *= -1;
}
else {
this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
}
}
// if the camera is set, rotate to the camera's rotation
this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
}
}
};
/**
* Attaches a mesh to the controller
* @param mesh the mesh to be attached
*/
PoseEnabledController.prototype.attachToMesh = function (mesh) {
if (this._mesh) {
this._mesh.parent = null;
}
this._mesh = mesh;
if (this._poseControlledCamera) {
this._mesh.parent = this._poseControlledCamera;
}
if (!this._mesh.rotationQuaternion) {
this._mesh.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
}
// Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
if (!this.isXR) {
this._updatePoseAndMesh();
if (this._pointingPoseNode) {
var parents = [];
var obj = this._pointingPoseNode;
while (obj.parent) {
parents.push(obj.parent);
obj = obj.parent;
}
parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
}
}
this._meshAttachedObservable.notifyObservers(mesh);
};
/**
* Attaches the controllers mesh to a camera
* @param camera the camera the mesh should be attached to
*/
PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
this._poseControlledCamera = camera;
if (this._mesh) {
this._mesh.parent = this._poseControlledCamera;
}
};
/**
* Disposes of the controller
*/
PoseEnabledController.prototype.dispose = function () {
if (this._mesh) {
this._mesh.dispose();
}
this._mesh = null;
_super.prototype.dispose.call(this);
};
Object.defineProperty(PoseEnabledController.prototype, "mesh", {
/**
* The mesh that is attached to the controller
*/
get: function () {
return this._mesh;
},
enumerable: false,
configurable: true
});
/**
* Gets the ray of the controller in the direction the controller is pointing
* @param length the length the resulting ray should be
* @returns a ray in the direction the controller is pointing
*/
PoseEnabledController.prototype.getForwardRay = function (length) {
if (length === void 0) { length = 100; }
if (!this.mesh) {
return new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 1), length);
}
var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
var origin = m.getTranslation();
var forward = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, -1);
var forwardWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormal(forward, m);
var direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(forwardWorld);
return new _Culling_ray__WEBPACK_IMPORTED_MODULE_3__["Ray"](origin, direction, length);
};
/**
* Name of the child mesh that can be used to cast a ray from the controller
*/
PoseEnabledController.POINTING_POSE = "POINTING_POSE";
return PoseEnabledController;
}(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_5__["Gamepad"]));
/***/ }),
/***/ "./Gamepads/Controllers/viveController.ts":
/*!************************************************!*\
!*** ./Gamepads/Controllers/viveController.ts ***!
\************************************************/
/*! exports provided: ViveController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return ViveController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/**
* Vive Controller
*/
var ViveController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ViveController, _super);
/**
* Creates a new ViveController from a gamepad
* @param vrGamepad the gamepad that the controller should be created from
*/
function ViveController(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerType"].VIVE;
_this._invertLeftStickY = true;
return _this;
}
/**
* Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
* @param scene scene in which to add meshes
* @param meshLoaded optional callback function that will be called if the mesh loads successfully.
*/
ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
var _this = this;
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_1__["SceneLoader"].ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
/*
Parent Mesh name: ViveWand
- body
- r_gripper
- l_gripper
- menu_button
- system_button
- trackpad
- trigger
- LED
*/
_this._defaultModel = newMeshes[1];
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
});
};
Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
/**
* Fired when the left button on this controller is modified
*/
get: function () {
return this.onMainButtonStateChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
/**
* Fired when the right button on this controller is modified
*/
get: function () {
return this.onMainButtonStateChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
/**
* Fired when the menu button on this controller is modified
*/
get: function () {
return this.onSecondaryButtonStateChangedObservable;
},
enumerable: false,
configurable: true
});
/**
* Called once for each button that changed state since the last frame
* Vive mapping:
* 0: touchpad
* 1: trigger
* 2: left AND right buttons
* 3: menu button
* @param buttonIdx Which button index changed
* @param state New state of the button
* @param changes Which properties on the state changed since last frame
*/
ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
var notifyObject = state; //{ state: state, changes: changes };
switch (buttonIdx) {
case 0:
this.onPadStateChangedObservable.notifyObservers(notifyObject);
return;
case 1: // index trigger
if (this._defaultModel) {
(this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
}
this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
return;
case 2: // left AND right button
this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
return;
case 3:
if (this._defaultModel) {
if (notifyObject.pressed) {
(this._defaultModel.getChildren()[2]).position.y = -0.001;
}
else {
(this._defaultModel.getChildren()[2]).position.y = 0;
}
}
this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
return;
}
};
/**
* Base Url for the controller model.
*/
ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
/**
* File name for the controller model.
*/
ViveController.MODEL_FILENAME = 'wand.babylon';
return ViveController;
}(_webVRController__WEBPACK_IMPORTED_MODULE_2__["WebVRController"]));
_poseEnabledController__WEBPACK_IMPORTED_MODULE_3__["PoseEnabledControllerHelper"]._ControllerFactories.push({
canCreate: function (gamepadInfo) {
return gamepadInfo.id.toLowerCase().indexOf('openvr') !== -1;
},
create: function (gamepadInfo) {
return new ViveController(gamepadInfo);
}
});
/***/ }),
/***/ "./Gamepads/Controllers/webVRController.ts":
/*!*************************************************!*\
!*** ./Gamepads/Controllers/webVRController.ts ***!
\*************************************************/
/*! exports provided: WebVRController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return WebVRController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/**
* Defines the WebVRController object that represents controllers tracked in 3D space
*/
var WebVRController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WebVRController, _super);
/**
* Creates a new WebVRController from a gamepad
* @param vrGamepad the gamepad that the WebVRController should be created from
*/
function WebVRController(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
// Observables
/**
* Fired when the trigger state has changed
*/
_this.onTriggerStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when the main button state has changed
*/
_this.onMainButtonStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when the secondary button state has changed
*/
_this.onSecondaryButtonStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when the pad state has changed
*/
_this.onPadStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when controllers stick values have changed
*/
_this.onPadValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* X and Y axis corresponding to the controllers joystick
*/
_this.pad = { x: 0, y: 0 };
// avoid GC, store state in a tmp object
_this._changes = {
pressChanged: false,
touchChanged: false,
valueChanged: false,
changed: false
};
_this._buttons = new Array(vrGamepad.buttons.length);
_this.hand = vrGamepad.hand;
return _this;
}
/**
* Fired when a controller button's state has changed
* @param callback the callback containing the button that was modified
*/
WebVRController.prototype.onButtonStateChange = function (callback) {
this._onButtonStateChange = callback;
};
Object.defineProperty(WebVRController.prototype, "defaultModel", {
/**
* The default controller model for the controller
*/
get: function () {
return this._defaultModel;
},
enumerable: false,
configurable: true
});
/**
* Updates the state of the controller and mesh based on the current position and rotation of the controller
*/
WebVRController.prototype.update = function () {
_super.prototype.update.call(this);
for (var index = 0; index < this._buttons.length; index++) {
this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
}
if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
this.pad.x = this.leftStick.x;
this.pad.y = this.leftStick.y;
this.onPadValuesChangedObservable.notifyObservers(this.pad);
}
};
WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
if (!newState) {
newState = {
pressed: false,
touched: false,
value: 0
};
}
if (!currentState) {
this._buttons[buttonIndex] = {
pressed: newState.pressed,
touched: newState.touched,
value: newState.value
};
return;
}
this._checkChanges(newState, currentState);
if (this._changes.changed) {
this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
this._handleButtonChange(buttonIndex, newState, this._changes);
}
this._buttons[buttonIndex].pressed = newState.pressed;
this._buttons[buttonIndex].touched = newState.touched;
// oculus triggers are never 0, thou not touched.
this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
};
WebVRController.prototype._checkChanges = function (newState, currentState) {
this._changes.pressChanged = newState.pressed !== currentState.pressed;
this._changes.touchChanged = newState.touched !== currentState.touched;
this._changes.valueChanged = newState.value !== currentState.value;
this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
return this._changes;
};
/**
* Disposes of th webVRCOntroller
*/
WebVRController.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this._defaultModel = null;
this.onTriggerStateChangedObservable.clear();
this.onMainButtonStateChangedObservable.clear();
this.onSecondaryButtonStateChangedObservable.clear();
this.onPadStateChangedObservable.clear();
this.onPadValuesChangedObservable.clear();
};
return WebVRController;
}(_poseEnabledController__WEBPACK_IMPORTED_MODULE_2__["PoseEnabledController"]));
/***/ }),
/***/ "./Gamepads/Controllers/windowsMotionController.ts":
/*!*********************************************************!*\
!*** ./Gamepads/Controllers/windowsMotionController.ts ***!
\*********************************************************/
/*! exports provided: WindowsMotionController, XRWindowsMotionController */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return WindowsMotionController; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "XRWindowsMotionController", function() { return XRWindowsMotionController; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Culling/ray */ "./Culling/ray.ts");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _webVRController__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./webVRController */ "./Gamepads/Controllers/webVRController.ts");
/* harmony import */ var _genericController__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./genericController */ "./Gamepads/Controllers/genericController.ts");
/* harmony import */ var _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/**
* Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
*/
var LoadedMeshInfo = /** @class */ (function () {
function LoadedMeshInfo() {
/**
* Map of the button meshes contained in the controller
*/
this.buttonMeshes = {};
/**
* Map of the axis meshes contained in the controller
*/
this.axisMeshes = {};
}
return LoadedMeshInfo;
}());
/**
* Defines the WindowsMotionController object that the state of the windows motion controller
*/
var WindowsMotionController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WindowsMotionController, _super);
/**
* Creates a new WindowsMotionController from a gamepad
* @param vrGamepad the gamepad that the controller should be created from
*/
function WindowsMotionController(vrGamepad) {
var _this = _super.call(this, vrGamepad) || this;
_this._mapping = {
// Semantic button names
buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
// trigger, grip, trackpad, thumbstick, menu
// A mapping of the button name to glTF model node name
// that should be transformed by button value.
buttonMeshNames: {
'trigger': 'SELECT',
'menu': 'MENU',
'grip': 'GRASP',
'thumbstick': 'THUMBSTICK_PRESS',
'trackpad': 'TOUCHPAD_PRESS'
},
// This mapping is used to translate from the Motion Controller to Babylon semantics
buttonObservableNames: {
'trigger': 'onTriggerStateChangedObservable',
'menu': 'onSecondaryButtonStateChangedObservable',
'grip': 'onMainButtonStateChangedObservable',
'thumbstick': 'onPadStateChangedObservable',
'trackpad': 'onTrackpadChangedObservable'
},
// A mapping of the axis name to glTF model node name
// that should be transformed by axis value.
// This array mirrors the browserGamepad.axes array, such that
// the mesh corresponding to axis 0 is in this array index 0.
axisMeshNames: [
'THUMBSTICK_X',
'THUMBSTICK_Y',
'TOUCHPAD_TOUCH_X',
'TOUCHPAD_TOUCH_Y'
],
// upside down in webxr
pointingPoseMeshName: _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledController"].POINTING_POSE
};
/**
* Fired when the trackpad on this controller is clicked
*/
_this.onTrackpadChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Fired when the trackpad on this controller is modified
*/
_this.onTrackpadValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* The current x and y values of this controller's trackpad
*/
_this.trackpad = { x: 0, y: 0 };
_this.controllerType = _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledControllerType"].WINDOWS;
_this._loadedMeshInfo = null;
return _this;
}
Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
/**
* Fired when the trigger on this controller is modified
*/
get: function () {
return this.onTriggerStateChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
/**
* Fired when the menu button on this controller is modified
*/
get: function () {
return this.onSecondaryButtonStateChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
/**
* Fired when the grip button on this controller is modified
*/
get: function () {
return this.onMainButtonStateChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
/**
* Fired when the thumbstick button on this controller is modified
*/
get: function () {
return this.onPadStateChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
/**
* Fired when the touchpad button on this controller is modified
*/
get: function () {
return this.onTrackpadChangedObservable;
},
enumerable: false,
configurable: true
});
Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
/**
* Fired when the touchpad values on this controller are modified
*/
get: function () {
return this.onTrackpadValuesChangedObservable;
},
enumerable: false,
configurable: true
});
WindowsMotionController.prototype._updateTrackpad = function () {
if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
this.trackpad.x = this.browserGamepad["axes"][this._mapping.axisMeshNames.indexOf('TOUCHPAD_TOUCH_X')];
this.trackpad.y = this.browserGamepad["axes"][this._mapping.axisMeshNames.indexOf('TOUCHPAD_TOUCH_Y')];
this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
}
};
/**
* Called once per frame by the engine.
*/
WindowsMotionController.prototype.update = function () {
_super.prototype.update.call(this);
if (this.browserGamepad.axes) {
this._updateTrackpad();
// Only need to animate axes if there is a loaded mesh
if (this._loadedMeshInfo) {
for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
}
}
}
};
/**
* Called once for each button that changed state since the last frame
* @param buttonIdx Which button index changed
* @param state New state of the button
* @param changes Which properties on the state changed since last frame
*/
WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
var buttonName = this._mapping.buttons[buttonIdx];
if (!buttonName) {
return;
}
// Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
this._updateTrackpad();
// Only emit events for buttons that we know how to map from index to name
var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
if (observable) {
observable.notifyObservers(state);
}
this._lerpButtonTransform(buttonName, state.value);
};
/**
* Moves the buttons on the controller mesh based on their current state
* @param buttonName the name of the button to move
* @param buttonValue the value of the button which determines the buttons new position
*/
WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
// If there is no loaded mesh, there is nothing to transform.
if (!this._loadedMeshInfo) {
return;
}
var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
if (!meshInfo || !meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
return;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
};
/**
* Moves the axis on the controller mesh based on its current state
* @param axis the index of the axis
* @param axisValue the value of the axis which determines the meshes new position
* @hidden
*/
WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
if (!this._loadedMeshInfo) {
return;
}
var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
if (!meshInfo) {
return;
}
if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
return;
}
// Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
var lerpValue = axisValue * 0.5 + 0.5;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
};
/**
* Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
* @param scene scene in which to add meshes
* @param meshLoaded optional callback function that will be called if the mesh loads successfully.
*/
WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
var _this = this;
if (forceDefault === void 0) { forceDefault = false; }
var path;
var filename;
// Checking if GLB loader is present
if (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__["SceneLoader"].IsPluginForExtensionAvailable(".glb")) {
// Determine the device specific folder based on the ID suffix
var device = 'default';
if (this.id && !forceDefault) {
var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
device = ((match && match[0]) || device);
}
// Hand
if (this.hand === 'left') {
filename = WindowsMotionController.MODEL_LEFT_FILENAME;
}
else { // Right is the default if no hand is specified
filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
}
path = WindowsMotionController.MODEL_BASE_URL + device + '/';
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
path = _genericController__WEBPACK_IMPORTED_MODULE_8__["GenericController"].MODEL_BASE_URL;
filename = _genericController__WEBPACK_IMPORTED_MODULE_8__["GenericController"].MODEL_FILENAME;
}
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_6__["SceneLoader"].ImportMesh("", path, filename, scene, function (meshes) {
// glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
_this._loadedMeshInfo = _this.processModel(scene, meshes);
if (!_this._loadedMeshInfo) {
return;
}
_this._defaultModel = _this._loadedMeshInfo.rootNode;
_this.attachToMesh(_this._defaultModel);
if (meshLoaded) {
meshLoaded(_this._defaultModel);
}
}, null, function (scene, message) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log(message);
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
if (!forceDefault) {
_this.initControllerMesh(scene, meshLoaded, true);
}
});
};
/**
* Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
* can be transformed by button presses and axes values, based on this._mapping.
*
* @param scene scene in which the meshes exist
* @param meshes list of meshes that make up the controller model to process
* @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
*/
WindowsMotionController.prototype.processModel = function (scene, meshes) {
var loadedMeshInfo = null;
// Create a new mesh to contain the glTF hierarchy
var parentMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"](this.id + " " + this.hand, scene);
// Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
var childMesh = null;
for (var i = 0; i < meshes.length; i++) {
var mesh = meshes[i];
if (!mesh.parent) {
// Exclude controller meshes from picking results
mesh.isPickable = false;
// Handle root node, attach to the new parentMesh
childMesh = mesh;
break;
}
}
if (childMesh) {
childMesh.setParent(parentMesh);
// Create our mesh info. Note that this method will always return non-null.
loadedMeshInfo = this.createMeshInfo(parentMesh);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Could not find root node in model file.');
}
return loadedMeshInfo;
};
WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
var loadedMeshInfo = new LoadedMeshInfo();
var i;
loadedMeshInfo.rootNode = rootNode;
// Reset the caches
loadedMeshInfo.buttonMeshes = {};
loadedMeshInfo.axisMeshes = {};
// Button Meshes
for (i = 0; i < this._mapping.buttons.length; i++) {
var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
if (!buttonMeshName) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
continue;
}
var buttonMesh = getChildByName(rootNode, buttonMeshName);
if (!buttonMesh) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing button mesh with name: ' + buttonMeshName);
continue;
}
var buttonMeshInfo = {
index: i,
value: getImmediateChildByName(buttonMesh, 'VALUE'),
pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
};
if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
}
else {
// If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
'(VALUE: ' + !!buttonMeshInfo.value +
', PRESSED: ' + !!buttonMeshInfo.pressed +
', UNPRESSED:' + !!buttonMeshInfo.unpressed +
')');
}
}
// Axis Meshes
for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
var axisMeshName = this._mapping.axisMeshNames[i];
if (!axisMeshName) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Log('Skipping unknown axis at index: ' + i);
continue;
}
var axisMesh = getChildByName(rootNode, axisMeshName);
if (!axisMesh) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing axis mesh with name: ' + axisMeshName);
continue;
}
var axisMeshInfo = {
index: i,
value: getImmediateChildByName(axisMesh, 'VALUE'),
min: getImmediateChildByName(axisMesh, 'MIN'),
max: getImmediateChildByName(axisMesh, 'MAX')
};
if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
}
else {
// If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
'(VALUE: ' + !!axisMeshInfo.value +
', MIN: ' + !!axisMeshInfo.min +
', MAX:' + !!axisMeshInfo.max +
')');
}
}
// Pointing Ray
loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
if (!loadedMeshInfo.pointingPoseNode) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
}
else {
this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
}
return loadedMeshInfo;
// Look through all children recursively. This will return null if no mesh exists with the given name.
function getChildByName(node, name) {
return node.getChildren(function (n) { return n.name === name; }, false)[0];
}
// Look through only immediate children. This will return null if no mesh exists with the given name.
function getImmediateChildByName(node, name) {
return node.getChildren(function (n) { return n.name == name; }, true)[0];
}
};
/**
* Gets the ray of the controller in the direction the controller is pointing
* @param length the length the resulting ray should be
* @returns a ray in the direction the controller is pointing
*/
WindowsMotionController.prototype.getForwardRay = function (length) {
if (length === void 0) { length = 100; }
if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
return _super.prototype.getForwardRay.call(this, length);
}
var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
var origin = m.getTranslation();
var forward = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, -1);
var forwardWorld = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformNormal(forward, m);
var direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Normalize(forwardWorld);
return new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](origin, direction, length);
};
/**
* Disposes of the controller
*/
WindowsMotionController.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onTrackpadChangedObservable.clear();
this.onTrackpadValuesChangedObservable.clear();
};
/**
* The base url used to load the left and right controller models
*/
WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
/**
* The name of the left controller model file
*/
WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
/**
* The name of the right controller model file
*/
WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
/**
* The controller name prefix for this controller type
*/
WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
/**
* The controller id pattern for this controller type
*/
WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
return WindowsMotionController;
}(_webVRController__WEBPACK_IMPORTED_MODULE_7__["WebVRController"]));
/**
* This class represents a new windows motion controller in XR.
*/
var XRWindowsMotionController = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(XRWindowsMotionController, _super);
/**
* Construct a new XR-Based windows motion controller
*
* @param gamepadInfo the gamepad object from the browser
*/
function XRWindowsMotionController(gamepadInfo) {
var _this = _super.call(this, gamepadInfo) || this;
/**
* Changing the original WIndowsMotionController mapping to fir the new mapping
*/
_this._mapping = {
// Semantic button names
buttons: ['trigger', 'grip', 'trackpad', 'thumbstick', 'menu'],
// trigger, grip, trackpad, thumbstick, menu
// A mapping of the button name to glTF model node name
// that should be transformed by button value.
buttonMeshNames: {
'trigger': 'SELECT',
'menu': 'MENU',
'grip': 'GRASP',
'thumbstick': 'THUMBSTICK_PRESS',
'trackpad': 'TOUCHPAD_PRESS'
},
// This mapping is used to translate from the Motion Controller to Babylon semantics
buttonObservableNames: {
'trigger': 'onTriggerStateChangedObservable',
'menu': 'onSecondaryButtonStateChangedObservable',
'grip': 'onMainButtonStateChangedObservable',
'thumbstick': 'onThumbstickStateChangedObservable',
'trackpad': 'onTrackpadChangedObservable'
},
// A mapping of the axis name to glTF model node name
// that should be transformed by axis value.
// This array mirrors the browserGamepad.axes array, such that
// the mesh corresponding to axis 0 is in this array index 0.
axisMeshNames: [
'TOUCHPAD_TOUCH_X',
'TOUCHPAD_TOUCH_Y',
'THUMBSTICK_X',
'THUMBSTICK_Y'
],
// upside down in webxr
pointingPoseMeshName: _poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledController"].POINTING_POSE
};
/**
* holds the thumbstick values (X,Y)
*/
_this.thumbstickValues = { x: 0, y: 0 };
/**
* Fired when the thumbstick on this controller is clicked
*/
_this.onThumbstickStateChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Fired when the thumbstick on this controller is modified
*/
_this.onThumbstickValuesChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Fired when the touchpad button on this controller is modified
*/
_this.onTrackpadChangedObservable = _this.onPadStateChangedObservable;
/**
* Fired when the touchpad values on this controller are modified
*/
_this.onTrackpadValuesChangedObservable = _this.onPadValuesChangedObservable;
return _this;
}
Object.defineProperty(XRWindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
/**
* Fired when the thumbstick button on this controller is modified
* here to prevent breaking changes
*/
get: function () {
return this.onThumbstickStateChangedObservable;
},
enumerable: false,
configurable: true
});
/**
* updating the thumbstick(!) and not the trackpad.
* This is named this way due to the difference between WebVR and XR and to avoid
* changing the parent class.
*/
XRWindowsMotionController.prototype._updateTrackpad = function () {
if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.thumbstickValues.x || this.browserGamepad.axes[3] != this.thumbstickValues.y)) {
this.trackpad.x = this.browserGamepad["axes"][2];
this.trackpad.y = this.browserGamepad["axes"][3];
this.onThumbstickValuesChangedObservable.notifyObservers(this.trackpad);
}
};
/**
* Disposes the class with joy
*/
XRWindowsMotionController.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onThumbstickStateChangedObservable.clear();
this.onThumbstickValuesChangedObservable.clear();
};
return XRWindowsMotionController;
}(WindowsMotionController));
_poseEnabledController__WEBPACK_IMPORTED_MODULE_9__["PoseEnabledControllerHelper"]._ControllerFactories.push({
canCreate: function (gamepadInfo) {
return gamepadInfo.id.indexOf(WindowsMotionController.GAMEPAD_ID_PREFIX) === 0;
},
create: function (gamepadInfo) {
return new WindowsMotionController(gamepadInfo);
}
});
/***/ }),
/***/ "./Gamepads/dualShockGamepad.ts":
/*!**************************************!*\
!*** ./Gamepads/dualShockGamepad.ts ***!
\**************************************/
/*! exports provided: DualShockButton, DualShockDpad, DualShockPad */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DualShockButton", function() { return DualShockButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DualShockDpad", function() { return DualShockDpad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DualShockPad", function() { return DualShockPad; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts");
/**
* Defines supported buttons for DualShock compatible gamepads
*/
var DualShockButton;
(function (DualShockButton) {
/** Cross */
DualShockButton[DualShockButton["Cross"] = 0] = "Cross";
/** Circle */
DualShockButton[DualShockButton["Circle"] = 1] = "Circle";
/** Square */
DualShockButton[DualShockButton["Square"] = 2] = "Square";
/** Triangle */
DualShockButton[DualShockButton["Triangle"] = 3] = "Triangle";
/** L1 */
DualShockButton[DualShockButton["L1"] = 4] = "L1";
/** R1 */
DualShockButton[DualShockButton["R1"] = 5] = "R1";
/** Share */
DualShockButton[DualShockButton["Share"] = 8] = "Share";
/** Options */
DualShockButton[DualShockButton["Options"] = 9] = "Options";
/** Left stick */
DualShockButton[DualShockButton["LeftStick"] = 10] = "LeftStick";
/** Right stick */
DualShockButton[DualShockButton["RightStick"] = 11] = "RightStick";
})(DualShockButton || (DualShockButton = {}));
/** Defines values for DualShock DPad */
var DualShockDpad;
(function (DualShockDpad) {
/** Up */
DualShockDpad[DualShockDpad["Up"] = 12] = "Up";
/** Down */
DualShockDpad[DualShockDpad["Down"] = 13] = "Down";
/** Left */
DualShockDpad[DualShockDpad["Left"] = 14] = "Left";
/** Right */
DualShockDpad[DualShockDpad["Right"] = 15] = "Right";
})(DualShockDpad || (DualShockDpad = {}));
/**
* Defines a DualShock gamepad
*/
var DualShockPad = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DualShockPad, _super);
/**
* Creates a new DualShock gamepad object
* @param id defines the id of this gamepad
* @param index defines its index
* @param gamepad defines the internal HTML gamepad object
*/
function DualShockPad(id, index, gamepad) {
var _this = _super.call(this, id.replace("STANDARD GAMEPAD", "SONY PLAYSTATION DUALSHOCK"), index, gamepad, 0, 1, 2, 3) || this;
_this._leftTrigger = 0;
_this._rightTrigger = 0;
/** Observable raised when a button is pressed */
_this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a button is released */
_this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a pad is pressed */
_this.onPadDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a pad is released */
_this.onPadUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this._buttonCross = 0;
_this._buttonCircle = 0;
_this._buttonSquare = 0;
_this._buttonTriangle = 0;
_this._buttonShare = 0;
_this._buttonOptions = 0;
_this._buttonL1 = 0;
_this._buttonR1 = 0;
_this._buttonLeftStick = 0;
_this._buttonRightStick = 0;
_this._dPadUp = 0;
_this._dPadDown = 0;
_this._dPadLeft = 0;
_this._dPadRight = 0;
_this.type = _gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"].DUALSHOCK;
return _this;
}
/**
* Defines the callback to call when left trigger is pressed
* @param callback defines the callback to use
*/
DualShockPad.prototype.onlefttriggerchanged = function (callback) {
this._onlefttriggerchanged = callback;
};
/**
* Defines the callback to call when right trigger is pressed
* @param callback defines the callback to use
*/
DualShockPad.prototype.onrighttriggerchanged = function (callback) {
this._onrighttriggerchanged = callback;
};
Object.defineProperty(DualShockPad.prototype, "leftTrigger", {
/**
* Gets the left trigger value
*/
get: function () {
return this._leftTrigger;
},
/**
* Sets the left trigger value
*/
set: function (newValue) {
if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
this._onlefttriggerchanged(newValue);
}
this._leftTrigger = newValue;
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "rightTrigger", {
/**
* Gets the right trigger value
*/
get: function () {
return this._rightTrigger;
},
/**
* Sets the right trigger value
*/
set: function (newValue) {
if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
this._onrighttriggerchanged(newValue);
}
this._rightTrigger = newValue;
},
enumerable: false,
configurable: true
});
/**
* Defines the callback to call when a button is pressed
* @param callback defines the callback to use
*/
DualShockPad.prototype.onbuttondown = function (callback) {
this._onbuttondown = callback;
};
/**
* Defines the callback to call when a button is released
* @param callback defines the callback to use
*/
DualShockPad.prototype.onbuttonup = function (callback) {
this._onbuttonup = callback;
};
/**
* Defines the callback to call when a pad is pressed
* @param callback defines the callback to use
*/
DualShockPad.prototype.ondpaddown = function (callback) {
this._ondpaddown = callback;
};
/**
* Defines the callback to call when a pad is released
* @param callback defines the callback to use
*/
DualShockPad.prototype.ondpadup = function (callback) {
this._ondpadup = callback;
};
DualShockPad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._onbuttondown) {
this._onbuttondown(buttonType);
}
this.onButtonDownObservable.notifyObservers(buttonType);
}
if (newValue === 0) {
if (this._onbuttonup) {
this._onbuttonup(buttonType);
}
this.onButtonUpObservable.notifyObservers(buttonType);
}
}
return newValue;
};
DualShockPad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._ondpaddown) {
this._ondpaddown(buttonType);
}
this.onPadDownObservable.notifyObservers(buttonType);
}
if (newValue === 0) {
if (this._ondpadup) {
this._ondpadup(buttonType);
}
this.onPadUpObservable.notifyObservers(buttonType);
}
}
return newValue;
};
Object.defineProperty(DualShockPad.prototype, "buttonCross", {
/**
* Gets the value of the `Cross` button
*/
get: function () {
return this._buttonCross;
},
/**
* Sets the value of the `Cross` button
*/
set: function (value) {
this._buttonCross = this._setButtonValue(value, this._buttonCross, DualShockButton.Cross);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonCircle", {
/**
* Gets the value of the `Circle` button
*/
get: function () {
return this._buttonCircle;
},
/**
* Sets the value of the `Circle` button
*/
set: function (value) {
this._buttonCircle = this._setButtonValue(value, this._buttonCircle, DualShockButton.Circle);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonSquare", {
/**
* Gets the value of the `Square` button
*/
get: function () {
return this._buttonSquare;
},
/**
* Sets the value of the `Square` button
*/
set: function (value) {
this._buttonSquare = this._setButtonValue(value, this._buttonSquare, DualShockButton.Square);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonTriangle", {
/**
* Gets the value of the `Triangle` button
*/
get: function () {
return this._buttonTriangle;
},
/**
* Sets the value of the `Triangle` button
*/
set: function (value) {
this._buttonTriangle = this._setButtonValue(value, this._buttonTriangle, DualShockButton.Triangle);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonOptions", {
/**
* Gets the value of the `Options` button
*/
get: function () {
return this._buttonOptions;
},
/**
* Sets the value of the `Options` button
*/
set: function (value) {
this._buttonOptions = this._setButtonValue(value, this._buttonOptions, DualShockButton.Options);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonShare", {
/**
* Gets the value of the `Share` button
*/
get: function () {
return this._buttonShare;
},
/**
* Sets the value of the `Share` button
*/
set: function (value) {
this._buttonShare = this._setButtonValue(value, this._buttonShare, DualShockButton.Share);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonL1", {
/**
* Gets the value of the `L1` button
*/
get: function () {
return this._buttonL1;
},
/**
* Sets the value of the `L1` button
*/
set: function (value) {
this._buttonL1 = this._setButtonValue(value, this._buttonL1, DualShockButton.L1);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonR1", {
/**
* Gets the value of the `R1` button
*/
get: function () {
return this._buttonR1;
},
/**
* Sets the value of the `R1` button
*/
set: function (value) {
this._buttonR1 = this._setButtonValue(value, this._buttonR1, DualShockButton.R1);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonLeftStick", {
/**
* Gets the value of the Left joystick
*/
get: function () {
return this._buttonLeftStick;
},
/**
* Sets the value of the Left joystick
*/
set: function (value) {
this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, DualShockButton.LeftStick);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "buttonRightStick", {
/**
* Gets the value of the Right joystick
*/
get: function () {
return this._buttonRightStick;
},
/**
* Sets the value of the Right joystick
*/
set: function (value) {
this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, DualShockButton.RightStick);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "dPadUp", {
/**
* Gets the value of D-pad up
*/
get: function () {
return this._dPadUp;
},
/**
* Sets the value of D-pad up
*/
set: function (value) {
this._dPadUp = this._setDPadValue(value, this._dPadUp, DualShockDpad.Up);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "dPadDown", {
/**
* Gets the value of D-pad down
*/
get: function () {
return this._dPadDown;
},
/**
* Sets the value of D-pad down
*/
set: function (value) {
this._dPadDown = this._setDPadValue(value, this._dPadDown, DualShockDpad.Down);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "dPadLeft", {
/**
* Gets the value of D-pad left
*/
get: function () {
return this._dPadLeft;
},
/**
* Sets the value of D-pad left
*/
set: function (value) {
this._dPadLeft = this._setDPadValue(value, this._dPadLeft, DualShockDpad.Left);
},
enumerable: false,
configurable: true
});
Object.defineProperty(DualShockPad.prototype, "dPadRight", {
/**
* Gets the value of D-pad right
*/
get: function () {
return this._dPadRight;
},
/**
* Sets the value of D-pad right
*/
set: function (value) {
this._dPadRight = this._setDPadValue(value, this._dPadRight, DualShockDpad.Right);
},
enumerable: false,
configurable: true
});
/**
* Force the gamepad to synchronize with device values
*/
DualShockPad.prototype.update = function () {
_super.prototype.update.call(this);
this.buttonCross = this.browserGamepad.buttons[0].value;
this.buttonCircle = this.browserGamepad.buttons[1].value;
this.buttonSquare = this.browserGamepad.buttons[2].value;
this.buttonTriangle = this.browserGamepad.buttons[3].value;
this.buttonL1 = this.browserGamepad.buttons[4].value;
this.buttonR1 = this.browserGamepad.buttons[5].value;
this.leftTrigger = this.browserGamepad.buttons[6].value;
this.rightTrigger = this.browserGamepad.buttons[7].value;
this.buttonShare = this.browserGamepad.buttons[8].value;
this.buttonOptions = this.browserGamepad.buttons[9].value;
this.buttonLeftStick = this.browserGamepad.buttons[10].value;
this.buttonRightStick = this.browserGamepad.buttons[11].value;
this.dPadUp = this.browserGamepad.buttons[12].value;
this.dPadDown = this.browserGamepad.buttons[13].value;
this.dPadLeft = this.browserGamepad.buttons[14].value;
this.dPadRight = this.browserGamepad.buttons[15].value;
};
/**
* Disposes the gamepad
*/
DualShockPad.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onButtonDownObservable.clear();
this.onButtonUpObservable.clear();
this.onPadDownObservable.clear();
this.onPadUpObservable.clear();
};
return DualShockPad;
}(_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"]));
/***/ }),
/***/ "./Gamepads/gamepad.ts":
/*!*****************************!*\
!*** ./Gamepads/gamepad.ts ***!
\*****************************/
/*! exports provided: StickValues, Gamepad, GenericPad */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return StickValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return Gamepad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return GenericPad; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/**
* Represents a gamepad control stick position
*/
var StickValues = /** @class */ (function () {
/**
* Initializes the gamepad x and y control stick values
* @param x The x component of the gamepad control stick value
* @param y The y component of the gamepad control stick value
*/
function StickValues(
/**
* The x component of the control stick
*/
x,
/**
* The y component of the control stick
*/
y) {
this.x = x;
this.y = y;
}
return StickValues;
}());
/**
* Represents a gamepad
*/
var Gamepad = /** @class */ (function () {
/**
* Initializes the gamepad
* @param id The id of the gamepad
* @param index The index of the gamepad
* @param browserGamepad The browser gamepad
* @param leftStickX The x component of the left joystick
* @param leftStickY The y component of the left joystick
* @param rightStickX The x component of the right joystick
* @param rightStickY The y component of the right joystick
*/
function Gamepad(
/**
* The id of the gamepad
*/
id,
/**
* The index of the gamepad
*/
index,
/**
* The browser gamepad
*/
browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
if (leftStickX === void 0) { leftStickX = 0; }
if (leftStickY === void 0) { leftStickY = 1; }
if (rightStickX === void 0) { rightStickX = 2; }
if (rightStickY === void 0) { rightStickY = 3; }
this.id = id;
this.index = index;
this.browserGamepad = browserGamepad;
this._leftStick = { x: 0, y: 0 };
this._rightStick = { x: 0, y: 0 };
/** @hidden */
this._isConnected = true;
/**
* Specifies whether the left control stick should be Y-inverted
*/
this._invertLeftStickY = false;
this.type = Gamepad.GAMEPAD;
this._leftStickAxisX = leftStickX;
this._leftStickAxisY = leftStickY;
this._rightStickAxisX = rightStickX;
this._rightStickAxisY = rightStickY;
if (this.browserGamepad.axes.length >= 2) {
this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
}
if (this.browserGamepad.axes.length >= 4) {
this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
}
}
Object.defineProperty(Gamepad.prototype, "isConnected", {
/**
* Specifies if the gamepad has been connected
*/
get: function () {
return this._isConnected;
},
enumerable: false,
configurable: true
});
/**
* Callback triggered when the left joystick has changed
* @param callback
*/
Gamepad.prototype.onleftstickchanged = function (callback) {
this._onleftstickchanged = callback;
};
/**
* Callback triggered when the right joystick has changed
* @param callback
*/
Gamepad.prototype.onrightstickchanged = function (callback) {
this._onrightstickchanged = callback;
};
Object.defineProperty(Gamepad.prototype, "leftStick", {
/**
* Gets the left joystick
*/
get: function () {
return this._leftStick;
},
/**
* Sets the left joystick values
*/
set: function (newValues) {
if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
this._onleftstickchanged(newValues);
}
this._leftStick = newValues;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Gamepad.prototype, "rightStick", {
/**
* Gets the right joystick
*/
get: function () {
return this._rightStick;
},
/**
* Sets the right joystick value
*/
set: function (newValues) {
if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
this._onrightstickchanged(newValues);
}
this._rightStick = newValues;
},
enumerable: false,
configurable: true
});
/**
* Updates the gamepad joystick positions
*/
Gamepad.prototype.update = function () {
if (this._leftStick) {
this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
if (this._invertLeftStickY) {
this.leftStick.y *= -1;
}
}
if (this._rightStick) {
this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
}
};
/**
* Disposes the gamepad
*/
Gamepad.prototype.dispose = function () {
};
/**
* Represents a gamepad controller
*/
Gamepad.GAMEPAD = 0;
/**
* Represents a generic controller
*/
Gamepad.GENERIC = 1;
/**
* Represents an XBox controller
*/
Gamepad.XBOX = 2;
/**
* Represents a pose-enabled controller
*/
Gamepad.POSE_ENABLED = 3;
/**
* Represents an Dual Shock controller
*/
Gamepad.DUALSHOCK = 4;
return Gamepad;
}());
/**
* Represents a generic gamepad
*/
var GenericPad = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GenericPad, _super);
/**
* Initializes the generic gamepad
* @param id The id of the generic gamepad
* @param index The index of the generic gamepad
* @param browserGamepad The browser gamepad
*/
function GenericPad(id, index, browserGamepad) {
var _this = _super.call(this, id, index, browserGamepad) || this;
/**
* Observable triggered when a button has been pressed
*/
_this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Observable triggered when a button has been released
*/
_this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this.type = Gamepad.GENERIC;
_this._buttons = new Array(browserGamepad.buttons.length);
return _this;
}
/**
* Callback triggered when a button has been pressed
* @param callback Called when a button has been pressed
*/
GenericPad.prototype.onbuttondown = function (callback) {
this._onbuttondown = callback;
};
/**
* Callback triggered when a button has been released
* @param callback Called when a button has been released
*/
GenericPad.prototype.onbuttonup = function (callback) {
this._onbuttonup = callback;
};
GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._onbuttondown) {
this._onbuttondown(buttonIndex);
}
this.onButtonDownObservable.notifyObservers(buttonIndex);
}
if (newValue === 0) {
if (this._onbuttonup) {
this._onbuttonup(buttonIndex);
}
this.onButtonUpObservable.notifyObservers(buttonIndex);
}
}
return newValue;
};
/**
* Updates the generic gamepad
*/
GenericPad.prototype.update = function () {
_super.prototype.update.call(this);
for (var index = 0; index < this._buttons.length; index++) {
this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
}
};
/**
* Disposes the generic gamepad
*/
GenericPad.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onButtonDownObservable.clear();
this.onButtonUpObservable.clear();
};
return GenericPad;
}(Gamepad));
/***/ }),
/***/ "./Gamepads/gamepadManager.ts":
/*!************************************!*\
!*** ./Gamepads/gamepadManager.ts ***!
\************************************/
/*! exports provided: GamepadManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return GamepadManager; });
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Misc_domManagement__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/domManagement */ "./Misc/domManagement.ts");
/* harmony import */ var _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gamepads/Controllers/poseEnabledController */ "./Gamepads/Controllers/poseEnabledController.ts");
/* harmony import */ var _xboxGamepad__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./xboxGamepad */ "./Gamepads/xboxGamepad.ts");
/* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _dualShockGamepad__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./dualShockGamepad */ "./Gamepads/dualShockGamepad.ts");
/**
* Manager for handling gamepads
*/
var GamepadManager = /** @class */ (function () {
/**
* Initializes the gamepad manager
* @param _scene BabylonJS scene
*/
function GamepadManager(_scene) {
var _this = this;
this._scene = _scene;
this._babylonGamepads = [];
this._oneGamepadConnected = false;
/** @hidden */
this._isMonitoring = false;
/**
* observable to be triggered when the gamepad controller has been disconnected
*/
this.onGamepadDisconnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
if (!_Misc_domManagement__WEBPACK_IMPORTED_MODULE_1__["DomManagement"].IsWindowObjectExist()) {
this._gamepadEventSupported = false;
}
else {
this._gamepadEventSupported = 'GamepadEvent' in window;
this._gamepadSupport = (navigator.getGamepads ||
navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
}
this.onGamepadConnectedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"](function (observer) {
// This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
for (var i in _this._babylonGamepads) {
var gamepad = _this._babylonGamepads[i];
if (gamepad && gamepad._isConnected) {
_this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
}
}
});
this._onGamepadConnectedEvent = function (evt) {
var gamepad = evt.gamepad;
if (gamepad.index in _this._babylonGamepads) {
if (_this._babylonGamepads[gamepad.index].isConnected) {
return;
}
}
var newGamepad;
if (_this._babylonGamepads[gamepad.index]) {
newGamepad = _this._babylonGamepads[gamepad.index];
newGamepad.browserGamepad = gamepad;
newGamepad._isConnected = true;
}
else {
newGamepad = _this._addNewGamepad(gamepad);
}
_this.onGamepadConnectedObservable.notifyObservers(newGamepad);
_this._startMonitoringGamepads();
};
this._onGamepadDisconnectedEvent = function (evt) {
var gamepad = evt.gamepad;
// Remove the gamepad from the list of gamepads to monitor.
for (var i in _this._babylonGamepads) {
if (_this._babylonGamepads[i].index === gamepad.index) {
var disconnectedGamepad = _this._babylonGamepads[i];
disconnectedGamepad._isConnected = false;
_this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
disconnectedGamepad.dispose && disconnectedGamepad.dispose();
break;
}
}
};
if (this._gamepadSupport) {
//first add already-connected gamepads
this._updateGamepadObjects();
if (this._babylonGamepads.length) {
this._startMonitoringGamepads();
}
// Checking if the gamepad connected event is supported (like in Firefox)
if (this._gamepadEventSupported) {
var hostWindow = this._scene ? this._scene.getEngine().getHostWindow() : window;
if (hostWindow) {
hostWindow.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
hostWindow.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
}
}
else {
this._startMonitoringGamepads();
}
}
}
Object.defineProperty(GamepadManager.prototype, "gamepads", {
/**
* The gamepads in the game pad manager
*/
get: function () {
return this._babylonGamepads;
},
enumerable: false,
configurable: true
});
/**
* Get the gamepad controllers based on type
* @param type The type of gamepad controller
* @returns Nullable gamepad
*/
GamepadManager.prototype.getGamepadByType = function (type) {
if (type === void 0) { type = _gamepad__WEBPACK_IMPORTED_MODULE_4__["Gamepad"].XBOX; }
for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
var gamepad = _a[_i];
if (gamepad && gamepad.type === type) {
return gamepad;
}
}
return null;
};
/**
* Disposes the gamepad manager
*/
GamepadManager.prototype.dispose = function () {
if (this._gamepadEventSupported) {
if (this._onGamepadConnectedEvent) {
window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
}
if (this._onGamepadDisconnectedEvent) {
window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
}
this._onGamepadConnectedEvent = null;
this._onGamepadDisconnectedEvent = null;
}
this._babylonGamepads.forEach(function (gamepad) {
gamepad.dispose();
});
this.onGamepadConnectedObservable.clear();
this.onGamepadDisconnectedObservable.clear();
this._oneGamepadConnected = false;
this._stopMonitoringGamepads();
this._babylonGamepads = [];
};
GamepadManager.prototype._addNewGamepad = function (gamepad) {
if (!this._oneGamepadConnected) {
this._oneGamepadConnected = true;
}
var newGamepad;
var dualShock = (gamepad.id.search("054c") !== -1);
var xboxOne = (gamepad.id.search("Xbox One") !== -1);
if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
newGamepad = new _xboxGamepad__WEBPACK_IMPORTED_MODULE_3__["Xbox360Pad"](gamepad.id, gamepad.index, gamepad, xboxOne);
}
else if (dualShock) {
newGamepad = new _dualShockGamepad__WEBPACK_IMPORTED_MODULE_6__["DualShockPad"](gamepad.id, gamepad.index, gamepad);
}
// if pose is supported, use the (WebVR) pose enabled controller
else if (gamepad.pose) {
newGamepad = _Gamepads_Controllers_poseEnabledController__WEBPACK_IMPORTED_MODULE_2__["PoseEnabledControllerHelper"].InitiateController(gamepad);
}
else {
newGamepad = new _gamepad__WEBPACK_IMPORTED_MODULE_4__["GenericPad"](gamepad.id, gamepad.index, gamepad);
}
this._babylonGamepads[newGamepad.index] = newGamepad;
return newGamepad;
};
GamepadManager.prototype._startMonitoringGamepads = function () {
if (!this._isMonitoring) {
this._isMonitoring = true;
//back-comp
if (!this._scene) {
this._checkGamepadsStatus();
}
}
};
GamepadManager.prototype._stopMonitoringGamepads = function () {
this._isMonitoring = false;
};
/** @hidden */
GamepadManager.prototype._checkGamepadsStatus = function () {
var _this = this;
// Hack to be compatible Chrome
this._updateGamepadObjects();
for (var i in this._babylonGamepads) {
var gamepad = this._babylonGamepads[i];
if (!gamepad || !gamepad.isConnected) {
continue;
}
gamepad.update();
}
if (this._isMonitoring && !this._scene) {
_Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].QueueNewFrame(function () { _this._checkGamepadsStatus(); });
}
};
// This function is called only on Chrome, which does not properly support
// connection/disconnection events and forces you to recopy again the gamepad object
GamepadManager.prototype._updateGamepadObjects = function () {
var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
for (var i = 0; i < gamepads.length; i++) {
var gamepad = gamepads[i];
if (gamepad) {
if (!this._babylonGamepads[gamepad.index]) {
var newGamepad = this._addNewGamepad(gamepad);
this.onGamepadConnectedObservable.notifyObservers(newGamepad);
}
else {
// Forced to copy again this object for Chrome for unknown reason
this._babylonGamepads[i].browserGamepad = gamepad;
if (!this._babylonGamepads[i].isConnected) {
this._babylonGamepads[i]._isConnected = true;
this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
}
}
}
}
};
return GamepadManager;
}());
/***/ }),
/***/ "./Gamepads/gamepadSceneComponent.ts":
/*!*******************************************!*\
!*** ./Gamepads/gamepadSceneComponent.ts ***!
\*******************************************/
/*! exports provided: GamepadSystemSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return GamepadSystemSceneComponent; });
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../scene */ "./scene.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _gamepadManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepadManager */ "./Gamepads/gamepadManager.ts");
/* harmony import */ var _Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Cameras/freeCameraInputsManager */ "./Cameras/freeCameraInputsManager.ts");
/* harmony import */ var _Cameras_Inputs_freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Cameras/Inputs/freeCameraGamepadInput */ "./Cameras/Inputs/freeCameraGamepadInput.ts");
/* harmony import */ var _Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Cameras/arcRotateCameraInputsManager */ "./Cameras/arcRotateCameraInputsManager.ts");
/* harmony import */ var _Cameras_Inputs_arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Cameras/Inputs/arcRotateCameraGamepadInput */ "./Cameras/Inputs/arcRotateCameraGamepadInput.ts");
Object.defineProperty(_scene__WEBPACK_IMPORTED_MODULE_0__["Scene"].prototype, "gamepadManager", {
get: function () {
if (!this._gamepadManager) {
this._gamepadManager = new _gamepadManager__WEBPACK_IMPORTED_MODULE_2__["GamepadManager"](this);
var component = this._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_GAMEPAD);
if (!component) {
component = new GamepadSystemSceneComponent(this);
this._addComponent(component);
}
}
return this._gamepadManager;
},
enumerable: true,
configurable: true
});
/**
* Adds a gamepad to the free camera inputs manager
*/
_Cameras_freeCameraInputsManager__WEBPACK_IMPORTED_MODULE_3__["FreeCameraInputsManager"].prototype.addGamepad = function () {
this.add(new _Cameras_Inputs_freeCameraGamepadInput__WEBPACK_IMPORTED_MODULE_4__["FreeCameraGamepadInput"]());
return this;
};
/**
* Adds a gamepad to the arc rotate camera inputs manager
*/
_Cameras_arcRotateCameraInputsManager__WEBPACK_IMPORTED_MODULE_5__["ArcRotateCameraInputsManager"].prototype.addGamepad = function () {
this.add(new _Cameras_Inputs_arcRotateCameraGamepadInput__WEBPACK_IMPORTED_MODULE_6__["ArcRotateCameraGamepadInput"]());
return this;
};
/**
* Defines the gamepad scene component responsible to manage gamepads in a given scene
*/
var GamepadSystemSceneComponent = /** @class */ (function () {
/**
* Creates a new instance of the component for the given scene
* @param scene Defines the scene to register the component in
*/
function GamepadSystemSceneComponent(scene) {
/**
* The component name helpfull to identify the component in the list of scene components.
*/
this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_GAMEPAD;
this.scene = scene;
}
/**
* Registers the component in a given scene
*/
GamepadSystemSceneComponent.prototype.register = function () {
this.scene._beforeCameraUpdateStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
GamepadSystemSceneComponent.prototype.rebuild = function () {
// Nothing to do for gamepads
};
/**
* Disposes the component and the associated ressources
*/
GamepadSystemSceneComponent.prototype.dispose = function () {
var gamepadManager = this.scene._gamepadManager;
if (gamepadManager) {
gamepadManager.dispose();
this.scene._gamepadManager = null;
}
};
GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
var gamepadManager = this.scene._gamepadManager;
if (gamepadManager && gamepadManager._isMonitoring) {
gamepadManager._checkGamepadsStatus();
}
};
return GamepadSystemSceneComponent;
}());
/***/ }),
/***/ "./Gamepads/index.ts":
/*!***************************!*\
!*** ./Gamepads/index.ts ***!
\***************************/
/*! exports provided: DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController, XRWindowsMotionController, StickValues, Gamepad, GenericPad, GamepadManager, GamepadSystemSceneComponent, Xbox360Button, Xbox360Dpad, Xbox360Pad, DualShockButton, DualShockDpad, DualShockPad */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Controllers_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Controllers/index */ "./Gamepads/Controllers/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["GearVRController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["GenericController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["OculusTouchController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["ViveController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["WebVRController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["WindowsMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "XRWindowsMotionController", function() { return _Controllers_index__WEBPACK_IMPORTED_MODULE_0__["XRWindowsMotionController"]; });
/* harmony import */ var _gamepad__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./gamepad */ "./Gamepads/gamepad.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["StickValues"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["Gamepad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return _gamepad__WEBPACK_IMPORTED_MODULE_1__["GenericPad"]; });
/* harmony import */ var _gamepadManager__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./gamepadManager */ "./Gamepads/gamepadManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return _gamepadManager__WEBPACK_IMPORTED_MODULE_2__["GamepadManager"]; });
/* harmony import */ var _gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./gamepadSceneComponent */ "./Gamepads/gamepadSceneComponent.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return _gamepadSceneComponent__WEBPACK_IMPORTED_MODULE_3__["GamepadSystemSceneComponent"]; });
/* harmony import */ var _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./xboxGamepad */ "./Gamepads/xboxGamepad.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Button"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Dpad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return _xboxGamepad__WEBPACK_IMPORTED_MODULE_4__["Xbox360Pad"]; });
/* harmony import */ var _dualShockGamepad__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./dualShockGamepad */ "./Gamepads/dualShockGamepad.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockButton", function() { return _dualShockGamepad__WEBPACK_IMPORTED_MODULE_5__["DualShockButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockDpad", function() { return _dualShockGamepad__WEBPACK_IMPORTED_MODULE_5__["DualShockDpad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockPad", function() { return _dualShockGamepad__WEBPACK_IMPORTED_MODULE_5__["DualShockPad"]; });
/***/ }),
/***/ "./Gamepads/xboxGamepad.ts":
/*!*********************************!*\
!*** ./Gamepads/xboxGamepad.ts ***!
\*********************************/
/*! exports provided: Xbox360Button, Xbox360Dpad, Xbox360Pad */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return Xbox360Button; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return Xbox360Dpad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return Xbox360Pad; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Gamepads/gamepad */ "./Gamepads/gamepad.ts");
/**
* Defines supported buttons for XBox360 compatible gamepads
*/
var Xbox360Button;
(function (Xbox360Button) {
/** A */
Xbox360Button[Xbox360Button["A"] = 0] = "A";
/** B */
Xbox360Button[Xbox360Button["B"] = 1] = "B";
/** X */
Xbox360Button[Xbox360Button["X"] = 2] = "X";
/** Y */
Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
/** Left button */
Xbox360Button[Xbox360Button["LB"] = 4] = "LB";
/** Right button */
Xbox360Button[Xbox360Button["RB"] = 5] = "RB";
/** Back */
Xbox360Button[Xbox360Button["Back"] = 8] = "Back";
/** Start */
Xbox360Button[Xbox360Button["Start"] = 9] = "Start";
/** Left stick */
Xbox360Button[Xbox360Button["LeftStick"] = 10] = "LeftStick";
/** Right stick */
Xbox360Button[Xbox360Button["RightStick"] = 11] = "RightStick";
})(Xbox360Button || (Xbox360Button = {}));
/** Defines values for XBox360 DPad */
var Xbox360Dpad;
(function (Xbox360Dpad) {
/** Up */
Xbox360Dpad[Xbox360Dpad["Up"] = 12] = "Up";
/** Down */
Xbox360Dpad[Xbox360Dpad["Down"] = 13] = "Down";
/** Left */
Xbox360Dpad[Xbox360Dpad["Left"] = 14] = "Left";
/** Right */
Xbox360Dpad[Xbox360Dpad["Right"] = 15] = "Right";
})(Xbox360Dpad || (Xbox360Dpad = {}));
/**
* Defines a XBox360 gamepad
*/
var Xbox360Pad = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Xbox360Pad, _super);
/**
* Creates a new XBox360 gamepad object
* @param id defines the id of this gamepad
* @param index defines its index
* @param gamepad defines the internal HTML gamepad object
* @param xboxOne defines if it is a XBox One gamepad
*/
function Xbox360Pad(id, index, gamepad, xboxOne) {
if (xboxOne === void 0) { xboxOne = false; }
var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
_this._leftTrigger = 0;
_this._rightTrigger = 0;
/** Observable raised when a button is pressed */
_this.onButtonDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a button is released */
_this.onButtonUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a pad is pressed */
_this.onPadDownObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/** Observable raised when a pad is released */
_this.onPadUpObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this._buttonA = 0;
_this._buttonB = 0;
_this._buttonX = 0;
_this._buttonY = 0;
_this._buttonBack = 0;
_this._buttonStart = 0;
_this._buttonLB = 0;
_this._buttonRB = 0;
_this._buttonLeftStick = 0;
_this._buttonRightStick = 0;
_this._dPadUp = 0;
_this._dPadDown = 0;
_this._dPadLeft = 0;
_this._dPadRight = 0;
_this._isXboxOnePad = false;
_this.type = _Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"].XBOX;
_this._isXboxOnePad = xboxOne;
return _this;
}
/**
* Defines the callback to call when left trigger is pressed
* @param callback defines the callback to use
*/
Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
this._onlefttriggerchanged = callback;
};
/**
* Defines the callback to call when right trigger is pressed
* @param callback defines the callback to use
*/
Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
this._onrighttriggerchanged = callback;
};
Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
/**
* Gets the left trigger value
*/
get: function () {
return this._leftTrigger;
},
/**
* Sets the left trigger value
*/
set: function (newValue) {
if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
this._onlefttriggerchanged(newValue);
}
this._leftTrigger = newValue;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
/**
* Gets the right trigger value
*/
get: function () {
return this._rightTrigger;
},
/**
* Sets the right trigger value
*/
set: function (newValue) {
if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
this._onrighttriggerchanged(newValue);
}
this._rightTrigger = newValue;
},
enumerable: false,
configurable: true
});
/**
* Defines the callback to call when a button is pressed
* @param callback defines the callback to use
*/
Xbox360Pad.prototype.onbuttondown = function (callback) {
this._onbuttondown = callback;
};
/**
* Defines the callback to call when a button is released
* @param callback defines the callback to use
*/
Xbox360Pad.prototype.onbuttonup = function (callback) {
this._onbuttonup = callback;
};
/**
* Defines the callback to call when a pad is pressed
* @param callback defines the callback to use
*/
Xbox360Pad.prototype.ondpaddown = function (callback) {
this._ondpaddown = callback;
};
/**
* Defines the callback to call when a pad is released
* @param callback defines the callback to use
*/
Xbox360Pad.prototype.ondpadup = function (callback) {
this._ondpadup = callback;
};
Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._onbuttondown) {
this._onbuttondown(buttonType);
}
this.onButtonDownObservable.notifyObservers(buttonType);
}
if (newValue === 0) {
if (this._onbuttonup) {
this._onbuttonup(buttonType);
}
this.onButtonUpObservable.notifyObservers(buttonType);
}
}
return newValue;
};
Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
if (newValue !== currentValue) {
if (newValue === 1) {
if (this._ondpaddown) {
this._ondpaddown(buttonType);
}
this.onPadDownObservable.notifyObservers(buttonType);
}
if (newValue === 0) {
if (this._ondpadup) {
this._ondpadup(buttonType);
}
this.onPadUpObservable.notifyObservers(buttonType);
}
}
return newValue;
};
Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
/**
* Gets the value of the `A` button
*/
get: function () {
return this._buttonA;
},
/**
* Sets the value of the `A` button
*/
set: function (value) {
this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
/**
* Gets the value of the `B` button
*/
get: function () {
return this._buttonB;
},
/**
* Sets the value of the `B` button
*/
set: function (value) {
this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
/**
* Gets the value of the `X` button
*/
get: function () {
return this._buttonX;
},
/**
* Sets the value of the `X` button
*/
set: function (value) {
this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
/**
* Gets the value of the `Y` button
*/
get: function () {
return this._buttonY;
},
/**
* Sets the value of the `Y` button
*/
set: function (value) {
this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
/**
* Gets the value of the `Start` button
*/
get: function () {
return this._buttonStart;
},
/**
* Sets the value of the `Start` button
*/
set: function (value) {
this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
/**
* Gets the value of the `Back` button
*/
get: function () {
return this._buttonBack;
},
/**
* Sets the value of the `Back` button
*/
set: function (value) {
this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
/**
* Gets the value of the `Left` button
*/
get: function () {
return this._buttonLB;
},
/**
* Sets the value of the `Left` button
*/
set: function (value) {
this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
/**
* Gets the value of the `Right` button
*/
get: function () {
return this._buttonRB;
},
/**
* Sets the value of the `Right` button
*/
set: function (value) {
this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
/**
* Gets the value of the Left joystick
*/
get: function () {
return this._buttonLeftStick;
},
/**
* Sets the value of the Left joystick
*/
set: function (value) {
this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
/**
* Gets the value of the Right joystick
*/
get: function () {
return this._buttonRightStick;
},
/**
* Sets the value of the Right joystick
*/
set: function (value) {
this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
/**
* Gets the value of D-pad up
*/
get: function () {
return this._dPadUp;
},
/**
* Sets the value of D-pad up
*/
set: function (value) {
this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
/**
* Gets the value of D-pad down
*/
get: function () {
return this._dPadDown;
},
/**
* Sets the value of D-pad down
*/
set: function (value) {
this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
/**
* Gets the value of D-pad left
*/
get: function () {
return this._dPadLeft;
},
/**
* Sets the value of D-pad left
*/
set: function (value) {
this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
/**
* Gets the value of D-pad right
*/
get: function () {
return this._dPadRight;
},
/**
* Sets the value of D-pad right
*/
set: function (value) {
this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
},
enumerable: false,
configurable: true
});
/**
* Force the gamepad to synchronize with device values
*/
Xbox360Pad.prototype.update = function () {
_super.prototype.update.call(this);
if (this._isXboxOnePad) {
this.buttonA = this.browserGamepad.buttons[0].value;
this.buttonB = this.browserGamepad.buttons[1].value;
this.buttonX = this.browserGamepad.buttons[2].value;
this.buttonY = this.browserGamepad.buttons[3].value;
this.buttonLB = this.browserGamepad.buttons[4].value;
this.buttonRB = this.browserGamepad.buttons[5].value;
this.leftTrigger = this.browserGamepad.buttons[6].value;
this.rightTrigger = this.browserGamepad.buttons[7].value;
this.buttonBack = this.browserGamepad.buttons[8].value;
this.buttonStart = this.browserGamepad.buttons[9].value;
this.buttonLeftStick = this.browserGamepad.buttons[10].value;
this.buttonRightStick = this.browserGamepad.buttons[11].value;
this.dPadUp = this.browserGamepad.buttons[12].value;
this.dPadDown = this.browserGamepad.buttons[13].value;
this.dPadLeft = this.browserGamepad.buttons[14].value;
this.dPadRight = this.browserGamepad.buttons[15].value;
}
else {
this.buttonA = this.browserGamepad.buttons[0].value;
this.buttonB = this.browserGamepad.buttons[1].value;
this.buttonX = this.browserGamepad.buttons[2].value;
this.buttonY = this.browserGamepad.buttons[3].value;
this.buttonLB = this.browserGamepad.buttons[4].value;
this.buttonRB = this.browserGamepad.buttons[5].value;
this.leftTrigger = this.browserGamepad.buttons[6].value;
this.rightTrigger = this.browserGamepad.buttons[7].value;
this.buttonBack = this.browserGamepad.buttons[8].value;
this.buttonStart = this.browserGamepad.buttons[9].value;
this.buttonLeftStick = this.browserGamepad.buttons[10].value;
this.buttonRightStick = this.browserGamepad.buttons[11].value;
this.dPadUp = this.browserGamepad.buttons[12].value;
this.dPadDown = this.browserGamepad.buttons[13].value;
this.dPadLeft = this.browserGamepad.buttons[14].value;
this.dPadRight = this.browserGamepad.buttons[15].value;
}
};
/**
* Disposes the gamepad
*/
Xbox360Pad.prototype.dispose = function () {
_super.prototype.dispose.call(this);
this.onButtonDownObservable.clear();
this.onButtonUpObservable.clear();
this.onPadDownObservable.clear();
this.onPadUpObservable.clear();
};
return Xbox360Pad;
}(_Gamepads_gamepad__WEBPACK_IMPORTED_MODULE_2__["Gamepad"]));
/***/ }),
/***/ "./Gizmos/axisDragGizmo.ts":
/*!*********************************!*\
!*** ./Gizmos/axisDragGizmo.ts ***!
\*********************************/
/*! exports provided: AxisDragGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return AxisDragGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts");
/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts");
/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/**
* Single axis drag gizmo
*/
var AxisDragGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AxisDragGizmo, _super);
/**
* Creates an AxisDragGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param dragAxis The axis which the gizmo will be able to drag on
* @param color The color of the gizmo
* @param thickness display gizmo axis thickness
*/
function AxisDragGizmo(dragAxis, color, gizmoLayer, parent, thickness) {
if (color === void 0) { color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_9__["Color3"].Gray(); }
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (parent === void 0) { parent = null; }
if (thickness === void 0) { thickness = 1; }
var _this = _super.call(this, gizmoLayer) || this;
_this._pointerObserver = null;
/**
* Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
*/
_this.snapDistance = 0;
/**
* Event that fires each time the gizmo snaps to a new location.
* * snapDistance is the the change in distance
*/
_this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this._isEnabled = true;
_this._parent = null;
_this._parent = parent;
// Create Material
_this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this._coloredMaterial.diffuseColor = color;
_this._coloredMaterial.specularColor = color.subtract(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.1, 0.1, 0.1));
_this._hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_8__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this._hoverMaterial.diffuseColor = color.add(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_9__["Color3"](0.3, 0.3, 0.3));
// Build mesh on root node
_this._arrow = AxisDragGizmo._CreateArrow(gizmoLayer.utilityLayerScene, _this._coloredMaterial, thickness);
_this._arrow.lookAt(_this._rootMesh.position.add(dragAxis));
_this._arrow.scaling.scaleInPlace(1 / 3);
_this._arrow.parent = _this._rootMesh;
var currentSnapDragDistance = 0;
var tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var tmpSnapEvent = { snapDistance: 0 };
// Add drag behavior to handle events when the gizmo is dragged
_this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_5__["PointerDragBehavior"]({ dragAxis: dragAxis });
_this.dragBehavior.moveAttached = false;
_this._rootMesh.addBehavior(_this.dragBehavior);
var localDelta = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"]();
_this.dragBehavior.onDragObservable.add(function (event) {
if (_this.attachedNode) {
// Convert delta to local translation if it has a parent
if (_this.attachedNode.parent) {
_this.attachedNode.parent.getWorldMatrix().invertToRef(tmpMatrix);
tmpMatrix.setTranslationFromFloats(0, 0, 0);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
}
else {
localDelta.copyFrom(event.delta);
}
// Snapping logic
if (_this.snapDistance == 0) {
if (_this.attachedNode.position) { // Required for nodes like lights
_this.attachedNode.position.addInPlaceFromFloats(localDelta.x, localDelta.y, localDelta.z);
}
// use _worldMatrix to not force a matrix update when calling GetWorldMatrix especialy with Cameras
_this.attachedNode._worldMatrix.addTranslationFromFloats(localDelta.x, localDelta.y, localDelta.z);
_this.attachedNode.updateCache();
}
else {
currentSnapDragDistance += event.dragDistance;
if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
localDelta.normalizeToRef(tmpVector);
tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
_this.attachedNode._worldMatrix.addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z);
_this.attachedNode.updateCache();
tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
_this.onSnapObservable.notifyObservers(tmpSnapEvent);
}
}
_this._matrixChanged();
}
});
_this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) {
if (_this._customMeshSet) {
return;
}
var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
var material = isHovered ? _this._hoverMaterial : _this._coloredMaterial;
_this._rootMesh.getChildMeshes().forEach(function (m) {
m.material = material;
if (m.color) {
m.color = material.diffuseColor;
}
});
});
var light = gizmoLayer._getSharedGizmoLight();
light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false));
return _this;
}
/** @hidden */
AxisDragGizmo._CreateArrow = function (scene, material, thickness) {
if (thickness === void 0) { thickness = 1; }
var arrow = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene);
var cylinder = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0, height: 0.075, diameterBottom: 0.0375 * (1 + (thickness - 1) / 4), tessellation: 96 }, scene);
var line = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_4__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, scene);
line.material = material;
cylinder.parent = arrow;
line.parent = arrow;
// Position arrow pointing in its drag axis
cylinder.material = material;
cylinder.rotation.x = Math.PI / 2;
cylinder.position.z += 0.3;
line.position.z += 0.275 / 2;
line.rotation.x = Math.PI / 2;
return arrow;
};
/** @hidden */
AxisDragGizmo._CreateArrowInstance = function (scene, arrow) {
var instance = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_3__["TransformNode"]("arrow", scene);
for (var _i = 0, _a = arrow.getChildMeshes(); _i < _a.length; _i++) {
var mesh = _a[_i];
var childInstance = mesh.createInstance(mesh.name);
childInstance.parent = instance;
}
return instance;
};
AxisDragGizmo.prototype._attachedNodeChanged = function (value) {
if (this.dragBehavior) {
this.dragBehavior.enabled = value ? true : false;
}
};
Object.defineProperty(AxisDragGizmo.prototype, "isEnabled", {
get: function () {
return this._isEnabled;
},
/**
* If the gizmo is enabled
*/
set: function (value) {
this._isEnabled = value;
if (!value) {
this.attachedMesh = null;
this.attachedNode = null;
}
else {
if (this._parent) {
this.attachedMesh = this._parent.attachedMesh;
this.attachedNode = this._parent.attachedNode;
}
}
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
AxisDragGizmo.prototype.dispose = function () {
this.onSnapObservable.clear();
this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
this.dragBehavior.detach();
if (this._arrow) {
this._arrow.dispose();
}
[this._coloredMaterial, this._hoverMaterial].forEach(function (matl) {
if (matl) {
matl.dispose();
}
});
_super.prototype.dispose.call(this);
};
return AxisDragGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/axisScaleGizmo.ts":
/*!**********************************!*\
!*** ./Gizmos/axisScaleGizmo.ts ***!
\**********************************/
/*! exports provided: AxisScaleGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return AxisScaleGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts");
/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/**
* Single axis scale gizmo
*/
var AxisScaleGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AxisScaleGizmo, _super);
/**
* Creates an AxisScaleGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param dragAxis The axis which the gizmo will be able to scale on
* @param color The color of the gizmo
* @param thickness display gizmo axis thickness
*/
function AxisScaleGizmo(dragAxis, color, gizmoLayer, parent, thickness) {
if (color === void 0) { color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"].Gray(); }
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_9__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (parent === void 0) { parent = null; }
if (thickness === void 0) { thickness = 1; }
var _this = _super.call(this, gizmoLayer) || this;
_this._pointerObserver = null;
/**
* Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
*/
_this.snapDistance = 0;
/**
* Event that fires each time the gizmo snaps to a new location.
* * snapDistance is the the change in distance
*/
_this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* If the scaling operation should be done on all axis (default: false)
*/
_this.uniformScaling = false;
/**
* Custom sensitivity value for the drag strength
*/
_this.sensitivity = 1;
_this._isEnabled = true;
_this._parent = null;
_this._parent = parent;
// Create Material
_this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this._coloredMaterial.diffuseColor = color;
_this._coloredMaterial.specularColor = color.subtract(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.1, 0.1, 0.1));
_this._hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this._hoverMaterial.diffuseColor = color.add(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_10__["Color3"](0.3, 0.3, 0.3));
// Build mesh on root node
_this._arrow = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__["AbstractMesh"]("", gizmoLayer.utilityLayerScene);
var arrowMesh = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_4__["BoxBuilder"].CreateBox("yPosMesh", { size: 0.4 * (1 + (thickness - 1) / 4) }, gizmoLayer.utilityLayerScene);
var arrowTail = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_5__["CylinderBuilder"].CreateCylinder("cylinder", { diameterTop: 0.005 * thickness, height: 0.275, diameterBottom: 0.005 * thickness, tessellation: 96 }, gizmoLayer.utilityLayerScene);
arrowTail.material = _this._coloredMaterial;
_this._arrow.addChild(arrowMesh);
_this._arrow.addChild(arrowTail);
// Position arrow pointing in its drag axis
arrowMesh.scaling.scaleInPlace(0.1);
arrowMesh.material = _this._coloredMaterial;
arrowMesh.rotation.x = Math.PI / 2;
arrowMesh.position.z += 0.3;
arrowTail.position.z += 0.275 / 2;
arrowTail.rotation.x = Math.PI / 2;
_this._arrow.lookAt(_this._rootMesh.position.add(dragAxis));
_this._rootMesh.addChild(_this._arrow);
_this._arrow.scaling.scaleInPlace(1 / 3);
// Add drag behavior to handle events when the gizmo is dragged
_this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_7__["PointerDragBehavior"]({ dragAxis: dragAxis });
_this.dragBehavior.moveAttached = false;
_this._rootMesh.addBehavior(_this.dragBehavior);
var currentSnapDragDistance = 0;
var tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var tmpSnapEvent = { snapDistance: 0 };
_this.dragBehavior.onDragObservable.add(function (event) {
if (_this.attachedNode) {
// Drag strength is modified by the scale of the gizmo (eg. for small objects like boombox the strength will be increased to match the behavior of larger objects)
var dragStrength = _this.sensitivity * event.dragDistance * ((_this.scaleRatio * 3) / _this._rootMesh.scaling.length());
// Snapping logic
var snapped = false;
var dragSteps = 0;
if (_this.uniformScaling) {
_this.attachedNode.getWorldMatrix().decompose(tmpVector);
tmpVector.normalize();
if (tmpVector.y < 0) {
tmpVector.scaleInPlace(-1);
}
}
else {
tmpVector.copyFrom(dragAxis);
}
if (_this.snapDistance == 0) {
tmpVector.scaleToRef(dragStrength, tmpVector);
}
else {
currentSnapDragDistance += dragStrength;
if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
if (currentSnapDragDistance < 0) {
dragSteps *= -1;
}
currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
snapped = true;
}
else {
tmpVector.scaleInPlace(0);
}
}
var scalingMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"]();
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].ScalingToRef(1 + tmpVector.x, 1 + tmpVector.y, 1 + tmpVector.z, scalingMatrix);
_this.attachedNode.getWorldMatrix().copyFrom(scalingMatrix.multiply(_this.attachedNode.getWorldMatrix()));
if (snapped) {
tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
_this.onSnapObservable.notifyObservers(tmpSnapEvent);
}
_this._matrixChanged();
}
});
_this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) {
if (_this._customMeshSet) {
return;
}
var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
var material = isHovered ? _this._hoverMaterial : _this._coloredMaterial;
_this._rootMesh.getChildMeshes().forEach(function (m) {
m.material = material;
if (m.color) {
m.color = material.diffuseColor;
}
});
});
var light = gizmoLayer._getSharedGizmoLight();
light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes());
return _this;
}
AxisScaleGizmo.prototype._attachedNodeChanged = function (value) {
if (this.dragBehavior) {
this.dragBehavior.enabled = value ? true : false;
}
};
Object.defineProperty(AxisScaleGizmo.prototype, "isEnabled", {
get: function () {
return this._isEnabled;
},
/**
* If the gizmo is enabled
*/
set: function (value) {
this._isEnabled = value;
if (!value) {
this.attachedMesh = null;
this.attachedNode = null;
}
else {
if (this._parent) {
this.attachedMesh = this._parent.attachedMesh;
this.attachedNode = this._parent.attachedNode;
}
}
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
AxisScaleGizmo.prototype.dispose = function () {
this.onSnapObservable.clear();
this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
this.dragBehavior.detach();
if (this._arrow) {
this._arrow.dispose();
}
[this._coloredMaterial, this._hoverMaterial].forEach(function (matl) {
if (matl) {
matl.dispose();
}
});
_super.prototype.dispose.call(this);
};
/**
* Disposes and replaces the current meshes in the gizmo with the specified mesh
* @param mesh The mesh to replace the default mesh of the gizmo
* @param useGizmoMaterial If the gizmo's default material should be used (default: false)
*/
AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
var _this = this;
if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
_super.prototype.setCustomMesh.call(this, mesh);
if (useGizmoMaterial) {
this._rootMesh.getChildMeshes().forEach(function (m) {
m.material = _this._coloredMaterial;
if (m.color) {
m.color = _this._coloredMaterial.diffuseColor;
}
});
this._customMeshSet = false;
}
};
return AxisScaleGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_8__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/boundingBoxGizmo.ts":
/*!************************************!*\
!*** ./Gizmos/boundingBoxGizmo.ts ***!
\************************************/
/*! exports provided: BoundingBoxGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return BoundingBoxGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts");
/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts");
/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts");
/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Misc/pivotTools */ "./Misc/pivotTools.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Maths_math_constants__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Maths/math.constants */ "./Maths/math.constants.ts");
/**
* Bounding box gizmo
*/
var BoundingBoxGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BoundingBoxGizmo, _super);
/**
* Creates an BoundingBoxGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param color The color of the gizmo
*/
function BoundingBoxGizmo(color, gizmoLayer) {
if (color === void 0) { color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__["Color3"].Gray(); }
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_11__["UtilityLayerRenderer"].DefaultKeepDepthUtilityLayer; }
var _this = _super.call(this, gizmoLayer) || this;
_this._boundingDimensions = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 1, 1);
_this._renderObserver = null;
_this._pointerObserver = null;
_this._scaleDragSpeed = 0.2;
_this._tmpQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
_this._tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0);
_this._tmpRotationMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
/**
* If child meshes should be ignored when calculating the boudning box. This should be set to true to avoid perf hits with heavily nested meshes (Default: false)
*/
_this.ignoreChildren = false;
/**
* Returns true if a descendant should be included when computing the bounding box. When null, all descendants are included. If ignoreChildren is set this will be ignored. (Default: null)
*/
_this.includeChildPredicate = null;
/**
* The size of the rotation spheres attached to the bounding box (Default: 0.1)
*/
_this.rotationSphereSize = 0.1;
/**
* The size of the scale boxes attached to the bounding box (Default: 0.1)
*/
_this.scaleBoxSize = 0.1;
/**
* If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
*/
_this.fixedDragMeshScreenSize = false;
/**
* The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
*/
_this.fixedDragMeshScreenSizeDistanceFactor = 10;
/**
* Fired when a rotation sphere or scale box is dragged
*/
_this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when a scale box is dragged
*/
_this.onScaleBoxDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when a scale box drag is ended
*/
_this.onScaleBoxDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when a rotation sphere is dragged
*/
_this.onRotationSphereDragObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Fired when a rotation sphere drag is ended
*/
_this.onRotationSphereDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
/**
* Relative bounding box pivot used when scaling the attached node. When null object with scale from the opposite corner. 0.5,0.5,0.5 for center and 0.5,0,0.5 for bottom (Default: null)
*/
_this.scalePivot = null;
_this._existingMeshScale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"]();
// Dragging
_this._dragMesh = null;
_this.pointerDragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]();
// Do not update the gizmo's scale so it has a fixed size to the object its attached to
_this.updateScale = false;
_this._anchorMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("anchor", gizmoLayer.utilityLayerScene);
// Create Materials
_this.coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this.coloredMaterial.disableLighting = true;
_this.hoverColoredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_12__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this.hoverColoredMaterial.disableLighting = true;
// Build bounding box out of lines
_this._lineBoundingBox = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene);
_this._lineBoundingBox.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
var lines = [];
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, _this._boundingDimensions.z), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
lines.push(_Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_8__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
lines.forEach(function (l) {
l.color = color;
l.position.addInPlace(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
l.isPickable = false;
_this._lineBoundingBox.addChild(l);
});
_this._rootMesh.addChild(_this._lineBoundingBox);
_this.setColor(color);
// Create rotation spheres
_this._rotateSpheresParent = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene);
_this._rotateSpheresParent.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
var _loop_1 = function (i_1) {
var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_6__["SphereBuilder"].CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
sphere.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
sphere.material = this_1.coloredMaterial;
// Drag behavior
_dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]({});
_dragBehavior.moveAttached = false;
_dragBehavior.updateDragPlane = false;
sphere.addBehavior(_dragBehavior);
var startingTurnDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0);
var totalTurnAmountOfDrag = 0;
_dragBehavior.onDragStartObservable.add(function () {
startingTurnDirection.copyFrom(sphere.forward);
totalTurnAmountOfDrag = 0;
});
_dragBehavior.onDragObservable.add(function (event) {
_this.onRotationSphereDragObservable.notifyObservers({});
if (_this.attachedMesh) {
var originalParent = _this.attachedMesh.parent;
if (originalParent && (originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001))) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");
return;
}
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedMesh);
var worldDragDirection = startingTurnDirection;
// Project the world right on to the drag plane
var toSub = event.dragPlaneNormal.scale(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(event.dragPlaneNormal, worldDragDirection));
var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
// project drag delta on to the resulting drag axis and rotate based on that
var projectDist = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Dot(dragAxis, event.delta) < 0 ? Math.abs(event.delta.length()) : -Math.abs(event.delta.length());
// Make rotation relative to size of mesh.
projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
// Rotate based on axis
if (!_this.attachedMesh.rotationQuaternion) {
_this.attachedMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
}
if (!_this._anchorMesh.rotationQuaternion) {
_this._anchorMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
}
// Do not allow the object to turn more than a full circle
totalTurnAmountOfDrag += projectDist;
if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
if (i_1 >= 8) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
}
else if (i_1 >= 4) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
}
else {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
}
// Rotate around center of bounding box
_this._anchorMesh.addChild(_this.attachedMesh);
_this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
_this._anchorMesh.removeChild(_this.attachedMesh);
_this.attachedMesh.setParent(originalParent);
}
_this.updateBoundingBox();
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(_this.attachedMesh);
}
_this._updateDummy();
});
// Selection/deselection
_dragBehavior.onDragStartObservable.add(function () {
_this.onDragStartObservable.notifyObservers({});
_this._selectNode(sphere);
});
_dragBehavior.onDragEndObservable.add(function () {
_this.onRotationSphereDragEndObservable.notifyObservers({});
_this._selectNode(null);
_this._updateDummy();
});
this_1._rotateSpheresParent.addChild(sphere);
};
var this_1 = this, _dragBehavior;
for (var i_1 = 0; i_1 < 12; i_1++) {
_loop_1(i_1);
}
_this._rootMesh.addChild(_this._rotateSpheresParent);
// Create scale cubes
_this._scaleBoxesParent = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene);
_this._scaleBoxesParent.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
var _loop_2 = function () {
// create box for relevant axis
var zeroAxisCount = ((i === 1) ? 1 : 0) + ((j === 1) ? 1 : 0) + ((k === 1) ? 1 : 0);
if (zeroAxisCount === 1 || zeroAxisCount === 3) {
return "continue";
}
var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__["BoxBuilder"].CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
box.material = this_2.coloredMaterial;
box.metadata = zeroAxisCount === 2; // None homogenous scale handle
// Dragging logic
var dragAxis = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](i - 1, j - 1, k - 1).normalize();
_dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_9__["PointerDragBehavior"]({ dragAxis: dragAxis });
_dragBehavior.updateDragPlane = false;
_dragBehavior.moveAttached = false;
box.addBehavior(_dragBehavior);
_dragBehavior.onDragObservable.add(function (event) {
_this.onScaleBoxDragObservable.notifyObservers({});
if (_this.attachedMesh) {
var originalParent = _this.attachedMesh.parent;
if (originalParent && (originalParent.scaling && originalParent.scaling.isNonUniformWithinEpsilon(0.001))) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("BoundingBoxGizmo controls are not supported on child meshes with non-uniform parent scaling");
return;
}
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(_this.attachedMesh);
var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
var deltaScale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](relativeDragDistance, relativeDragDistance, relativeDragDistance);
if (zeroAxisCount === 2) {
// scale on 1 axis when using the anchor box in the face middle
deltaScale.x *= Math.abs(dragAxis.x);
deltaScale.y *= Math.abs(dragAxis.y);
deltaScale.z *= Math.abs(dragAxis.z);
}
deltaScale.scaleInPlace(_this._scaleDragSpeed);
_this.updateBoundingBox();
if (_this.scalePivot) {
_this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
// Move anchor to desired pivot point (Bottom left corner + dimension/2)
_this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
_this._anchorMesh.position.subtractInPlace(_this._tmpVector);
_this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
_this._anchorMesh.position.addInPlace(_this._tmpVector);
}
else {
// Scale from the position of the opposite corner
box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
_this._anchorMesh.position.subtractInPlace(_this._tmpVector);
}
_this._anchorMesh.addChild(_this.attachedMesh);
_this._anchorMesh.scaling.addInPlace(deltaScale);
if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
_this._anchorMesh.scaling.subtractInPlace(deltaScale);
}
_this._anchorMesh.removeChild(_this.attachedMesh);
_this.attachedMesh.setParent(originalParent);
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(_this.attachedMesh);
}
_this._updateDummy();
});
// Selection/deselection
_dragBehavior.onDragStartObservable.add(function () {
_this.onDragStartObservable.notifyObservers({});
_this._selectNode(box);
});
_dragBehavior.onDragEndObservable.add(function () {
_this.onScaleBoxDragEndObservable.notifyObservers({});
_this._selectNode(null);
_this._updateDummy();
});
this_2._scaleBoxesParent.addChild(box);
};
var this_2 = this, _dragBehavior;
for (var k = 0; k < 3; k++) {
_loop_2();
}
}
}
_this._rootMesh.addChild(_this._scaleBoxesParent);
// Hover color change
var pointerIds = new Array();
_this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) {
if (!pointerIds[pointerInfo.event.pointerId]) {
_this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
pointerIds[pointerInfo.event.pointerId] = mesh;
mesh.material = _this.hoverColoredMaterial;
}
});
}
else {
if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
pointerIds[pointerInfo.event.pointerId].material = _this.coloredMaterial;
delete pointerIds[pointerInfo.event.pointerId];
}
}
});
// Update bounding box positions
_this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
// Only update the bouding box if scaling has changed
if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
_this.updateBoundingBox();
}
else if (_this.fixedDragMeshScreenSize) {
_this._updateRotationSpheres();
_this._updateScaleBoxes();
}
// If dragg mesh is enabled and dragging, update the attached mesh pose to match the drag mesh
if (_this._dragMesh && _this.attachedMesh && _this.pointerDragBehavior.dragging) {
_this._lineBoundingBox.position.rotateByQuaternionToRef(_this._rootMesh.rotationQuaternion, _this._tmpVector);
_this.attachedMesh.setAbsolutePosition(_this._dragMesh.position.add(_this._tmpVector.scale(-1)));
}
});
_this.updateBoundingBox();
return _this;
}
/**
* Sets the color of the bounding box gizmo
* @param color the color to set
*/
BoundingBoxGizmo.prototype.setColor = function (color) {
this.coloredMaterial.emissiveColor = color;
this.hoverColoredMaterial.emissiveColor = color.clone().add(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__["Color3"](0.3, 0.3, 0.3));
this._lineBoundingBox.getChildren().forEach(function (l) {
if (l.color) {
l.color = color;
}
});
};
BoundingBoxGizmo.prototype._attachedNodeChanged = function (value) {
var _this = this;
if (value) {
// Reset anchor mesh to match attached mesh's scale
// This is needed to avoid invalid box/sphere position on first drag
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(value);
var originalParent = value.parent;
this._anchorMesh.addChild(value);
this._anchorMesh.removeChild(value);
value.setParent(originalParent);
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(value);
this.updateBoundingBox();
value.getChildMeshes(false).forEach(function (m) {
m.markAsDirty("scaling");
});
this.gizmoLayer.utilityLayerScene.onAfterRenderObservable.addOnce(function () {
_this._updateDummy();
});
}
};
BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
this._rotateSpheresParent.getChildMeshes()
.concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m) {
m.isVisible = (!selectedMesh || m == selectedMesh);
});
};
/**
* Updates the bounding box information for the Gizmo
*/
BoundingBoxGizmo.prototype.updateBoundingBox = function () {
if (this.attachedMesh) {
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RemoveAndStorePivotPoint(this.attachedMesh);
// Store original parent
var originalParent = this.attachedMesh.parent;
this.attachedMesh.setParent(null);
// Store original skelton override mesh
var originalSkeletonOverrideMesh = null;
if (this.attachedMesh.skeleton) {
originalSkeletonOverrideMesh = this.attachedMesh.skeleton.overrideMesh;
this.attachedMesh.skeleton.overrideMesh = null;
}
this._update();
// Rotate based on axis
if (!this.attachedMesh.rotationQuaternion) {
this.attachedMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
}
if (!this._anchorMesh.rotationQuaternion) {
this._anchorMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
}
this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
// Store original position and reset mesh to origin before computing the bounding box
this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
this._tmpVector.copyFrom(this.attachedMesh.position);
this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
this.attachedMesh.position.set(0, 0, 0);
// Update bounding dimensions/positions
var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
// Update gizmo to match bounding box scaling and rotation
// The position set here is the offset from the origin for the boundingbox when the attached mesh is at the origin
// The position of the gizmo is then set to the attachedMesh in gizmo._update
this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
this._lineBoundingBox.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
this._lineBoundingBox.computeWorldMatrix();
this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
// Restore position/rotation values
this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
this.attachedMesh.position.copyFrom(this._tmpVector);
// Restore original parent
this.attachedMesh.setParent(originalParent);
// Restore original skeleton override mesh
if (this.attachedMesh.skeleton) {
this.attachedMesh.skeleton.overrideMesh = originalSkeletonOverrideMesh;
}
}
this._updateRotationSpheres();
this._updateScaleBoxes();
if (this.attachedMesh) {
this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
_Misc_pivotTools__WEBPACK_IMPORTED_MODULE_13__["PivotTools"]._RestorePivotPoint(this.attachedMesh);
}
};
BoundingBoxGizmo.prototype._updateRotationSpheres = function () {
var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 2; j++) {
for (var k = 0; k < 2; k++) {
var index = ((i * 4) + (j * 2)) + k;
if (i == 0) {
rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
rotateSpheres[index].position.addInPlace(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
rotateSpheres[index].lookAt(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Right()).normalizeToNew().add(rotateSpheres[index].position));
}
if (i == 1) {
rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
rotateSpheres[index].position.addInPlace(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
rotateSpheres[index].lookAt(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Up()).normalizeToNew().add(rotateSpheres[index].position));
}
if (i == 2) {
rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
rotateSpheres[index].position.addInPlace(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
rotateSpheres[index].lookAt(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Cross(rotateSpheres[index].position.normalizeToNew(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Forward()).normalizeToNew().add(rotateSpheres[index].position));
}
if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
}
else {
rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
}
}
}
}
};
BoundingBoxGizmo.prototype._updateScaleBoxes = function () {
var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
var index = 0;
for (var i = 0; i < 3; i++) {
for (var j = 0; j < 3; j++) {
for (var k = 0; k < 3; k++) {
var zeroAxisCount = ((i === 1) ? 1 : 0) + ((j === 1) ? 1 : 0) + ((k === 1) ? 1 : 0);
if (zeroAxisCount === 1 || zeroAxisCount === 3) {
continue;
}
if (scaleBoxes[index]) {
scaleBoxes[index].position.set(this._boundingDimensions.x * (i / 2), this._boundingDimensions.y * (j / 2), this._boundingDimensions.z * (k / 2));
scaleBoxes[index].position.addInPlace(new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
if (this.fixedDragMeshScreenSize && this.gizmoLayer.utilityLayerScene.activeCamera) {
scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
}
else {
scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
}
}
index++;
}
}
}
};
/**
* Enables rotation on the specified axis and disables rotation on the others
* @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
*/
BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
if (i < 4) {
m.setEnabled(axis.indexOf("x") != -1);
}
else if (i < 8) {
m.setEnabled(axis.indexOf("y") != -1);
}
else {
m.setEnabled(axis.indexOf("z") != -1);
}
});
};
/**
* Enables/disables scaling
* @param enable if scaling should be enabled
* @param homogeneousScaling defines if scaling should only be homogeneous
*/
BoundingBoxGizmo.prototype.setEnabledScaling = function (enable, homogeneousScaling) {
if (homogeneousScaling === void 0) { homogeneousScaling = false; }
this._scaleBoxesParent.getChildMeshes().forEach(function (m, i) {
var enableMesh = enable;
// Disable heterogenous scale handles if requested.
if (homogeneousScaling && m.metadata === true) {
enableMesh = false;
}
m.setEnabled(enableMesh);
});
};
BoundingBoxGizmo.prototype._updateDummy = function () {
if (this._dragMesh) {
this._dragMesh.position.copyFrom(this._lineBoundingBox.getAbsolutePosition());
this._dragMesh.scaling.copyFrom(this._lineBoundingBox.scaling);
this._dragMesh.rotationQuaternion.copyFrom(this._rootMesh.rotationQuaternion);
}
};
/**
* Enables a pointer drag behavior on the bounding box of the gizmo
*/
BoundingBoxGizmo.prototype.enableDragBehavior = function () {
this._dragMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreateBox("dummy", 1, this.gizmoLayer.utilityLayerScene);
this._dragMesh.visibility = 0;
this._dragMesh.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"]();
this.pointerDragBehavior.useObjectOrientationForDragging = false;
this._dragMesh.addBehavior(this.pointerDragBehavior);
};
/**
* Disposes of the gizmo
*/
BoundingBoxGizmo.prototype.dispose = function () {
this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
this._lineBoundingBox.dispose();
this._rotateSpheresParent.dispose();
this._scaleBoxesParent.dispose();
if (this._dragMesh) {
this._dragMesh.dispose();
}
_super.prototype.dispose.call(this);
};
/**
* Makes a mesh not pickable and wraps the mesh inside of a bounding box mesh that is pickable. (This is useful to avoid picking within complex geometry)
* @param mesh the mesh to wrap in the bounding box mesh and make not pickable
* @returns the bounding box mesh with the passed in mesh as a child
*/
BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
var makeNotPickable = function (root) {
root.isPickable = false;
root.getChildMeshes().forEach(function (c) {
makeNotPickable(c);
});
};
makeNotPickable(mesh);
// Reset position to get boudning box from origin with no rotation
if (!mesh.rotationQuaternion) {
mesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Quaternion"].RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
}
var oldPos = mesh.position.clone();
var oldRot = mesh.rotationQuaternion.clone();
mesh.rotationQuaternion.set(0, 0, 0, 1);
mesh.position.set(0, 0, 0);
// Update bounding dimensions/positions
var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_7__["BoxBuilder"].CreateBox("box", { size: 1 }, mesh.getScene());
var boundingMinMax = mesh.getHierarchyBoundingVectors();
boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
// Adjust scale to avoid undefined behavior when adding child
if (box.scaling.y === 0) {
box.scaling.y = _Maths_math_constants__WEBPACK_IMPORTED_MODULE_15__["Epsilon"];
}
if (box.scaling.x === 0) {
box.scaling.x = _Maths_math_constants__WEBPACK_IMPORTED_MODULE_15__["Epsilon"];
}
if (box.scaling.z === 0) {
box.scaling.z = _Maths_math_constants__WEBPACK_IMPORTED_MODULE_15__["Epsilon"];
}
box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
// Restore original positions
mesh.addChild(box);
mesh.rotationQuaternion.copyFrom(oldRot);
mesh.position.copyFrom(oldPos);
// Reverse parenting
mesh.removeChild(box);
box.addChild(mesh);
box.visibility = 0;
return box;
};
/**
* CustomMeshes are not supported by this gizmo
* @param mesh The mesh to replace the default mesh of the gizmo
*/
BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Error("Custom meshes are not supported on this gizmo");
};
return BoundingBoxGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_10__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/cameraGizmo.ts":
/*!*******************************!*\
!*** ./Gizmos/cameraGizmo.ts ***!
\*******************************/
/*! exports provided: CameraGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraGizmo", function() { return CameraGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts");
/* harmony import */ var _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Meshes/Builders/cylinderBuilder */ "./Meshes/Builders/cylinderBuilder.ts");
/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts");
/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts");
/**
* Gizmo that enables viewing a camera
*/
var CameraGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CameraGizmo, _super);
/**
* Creates a CameraGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
*/
function CameraGizmo(gizmoLayer) {
var _this = _super.call(this, gizmoLayer) || this;
_this._camera = null;
_this._invProjection = new _Maths_math__WEBPACK_IMPORTED_MODULE_8__["Matrix"]();
_this._material = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]("cameraGizmoMaterial", _this.gizmoLayer.utilityLayerScene);
_this._material.diffuseColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.5, 0.5, 0.5);
_this._material.specularColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1);
return _this;
}
Object.defineProperty(CameraGizmo.prototype, "displayFrustum", {
/** Gets or sets a boolean indicating if frustum lines must be rendered (true by default)) */
get: function () {
return this._cameraLinesMesh.isEnabled();
},
set: function (value) {
this._cameraLinesMesh.setEnabled(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(CameraGizmo.prototype, "camera", {
get: function () {
return this._camera;
},
/**
* The camera that the gizmo is attached to
*/
set: function (camera) {
var _this = this;
this._camera = camera;
this.attachedNode = camera;
if (camera) {
// Create the mesh for the given camera
if (this._cameraMesh) {
this._cameraMesh.dispose();
}
if (this._cameraLinesMesh) {
this._cameraLinesMesh.dispose();
}
this._cameraMesh = CameraGizmo._CreateCameraMesh(this.gizmoLayer.utilityLayerScene);
this._cameraLinesMesh = CameraGizmo._CreateCameraFrustum(this.gizmoLayer.utilityLayerScene);
this._cameraMesh.getChildMeshes(false).forEach(function (m) {
m.material = _this._material;
});
this._cameraMesh.parent = this._rootMesh;
this._cameraLinesMesh.parent = this._rootMesh;
if (this.gizmoLayer.utilityLayerScene.activeCamera && this.gizmoLayer.utilityLayerScene.activeCamera.maxZ < camera.maxZ * 1.5) {
this.gizmoLayer.utilityLayerScene.activeCamera.maxZ = camera.maxZ * 1.5;
}
if (!this.attachedNode.reservedDataStore) {
this.attachedNode.reservedDataStore = {};
}
this.attachedNode.reservedDataStore.cameraGizmo = this;
// Add lighting to the camera gizmo
var gizmoLight = this.gizmoLayer._getSharedGizmoLight();
gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._cameraMesh.getChildMeshes(false));
this._update();
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(CameraGizmo.prototype, "material", {
/**
* Gets the material used to render the camera gizmo
*/
get: function () {
return this._material;
},
enumerable: false,
configurable: true
});
/**
* @hidden
* Updates the gizmo to match the attached mesh's position/rotation
*/
CameraGizmo.prototype._update = function () {
_super.prototype._update.call(this);
if (!this._camera) {
return;
}
// frustum matrix
this._camera.getProjectionMatrix().invertToRef(this._invProjection);
this._cameraLinesMesh.setPivotMatrix(this._invProjection, false);
this._cameraLinesMesh.scaling.x = 1 / this._rootMesh.scaling.x;
this._cameraLinesMesh.scaling.y = 1 / this._rootMesh.scaling.y;
this._cameraLinesMesh.scaling.z = 1 / this._rootMesh.scaling.z;
// take care of coordinate system in camera scene to properly display the mesh with the good Y axis orientation in this scene
this._cameraMesh.parent = null;
this._cameraMesh.rotation.y = Math.PI * 0.5 * (this._camera.getScene().useRightHandedSystem ? 1 : -1);
this._cameraMesh.parent = this._rootMesh;
};
/**
* Disposes of the camera gizmo
*/
CameraGizmo.prototype.dispose = function () {
if (this._cameraMesh) {
this._cameraMesh.dispose();
}
if (this._cameraLinesMesh) {
this._cameraLinesMesh.dispose();
}
this._material.dispose();
_super.prototype.dispose.call(this);
};
CameraGizmo._CreateCameraMesh = function (scene) {
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("rootCameraGizmo", scene);
var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"](root.name, scene);
mesh.parent = root;
var box = _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_6__["BoxBuilder"].CreateBox(root.name, { width: 1.0, height: 0.8, depth: 0.5 }, scene);
box.parent = mesh;
var cyl1 = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_7__["CylinderBuilder"].CreateCylinder(root.name, { height: 0.5, diameterTop: 0.8, diameterBottom: 0.8 }, scene);
cyl1.parent = mesh;
cyl1.position.y = 0.3;
cyl1.position.x = -0.6;
cyl1.rotation.x = Math.PI * 0.5;
var cyl2 = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_7__["CylinderBuilder"].CreateCylinder(root.name, { height: 0.5, diameterTop: 0.6, diameterBottom: 0.6 }, scene);
cyl2.parent = mesh;
cyl2.position.y = 0.5;
cyl2.position.x = 0.4;
cyl2.rotation.x = Math.PI * 0.5;
var cyl3 = _Meshes_Builders_cylinderBuilder__WEBPACK_IMPORTED_MODULE_7__["CylinderBuilder"].CreateCylinder(root.name, { height: 0.5, diameterTop: 0.5, diameterBottom: 0.5 }, scene);
cyl3.parent = mesh;
cyl3.position.y = 0.0;
cyl3.position.x = 0.6;
cyl3.rotation.z = Math.PI * 0.5;
root.scaling.scaleInPlace(CameraGizmo._Scale);
mesh.position.x = -0.9;
return root;
};
CameraGizmo._CreateCameraFrustum = function (scene) {
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"]("rootCameraGizmo", scene);
var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"](root.name, scene);
mesh.parent = root;
for (var y = 0; y < 4; y += 2) {
for (var x = 0; x < 4; x += 2) {
var line = _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_9__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1 + x, -1 + y, -1), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1 + x, -1 + y, 1)] }, scene);
line.parent = mesh;
line.alwaysSelectAsActiveMesh = true;
line.isPickable = false;
var line = _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_9__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1, -1 + x, -1 + y), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](1, -1 + x, -1 + y)] }, scene);
line.parent = mesh;
line.alwaysSelectAsActiveMesh = true;
line.isPickable = false;
var line = _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_9__["LinesBuilder"].CreateLines("lines", { points: [new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1 + x, -1, -1 + y), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1 + x, 1, -1 + y)] }, scene);
line.parent = mesh;
line.alwaysSelectAsActiveMesh = true;
line.isPickable = false;
}
}
return root;
};
// Static helper methods
CameraGizmo._Scale = 0.05;
return CameraGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_4__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/gizmo.ts":
/*!*************************!*\
!*** ./Gizmos/gizmo.ts ***!
\*************************/
/*! exports provided: Gizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return Gizmo; });
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/**
* Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
*/
var Gizmo = /** @class */ (function () {
/**
* Creates a gizmo
* @param gizmoLayer The utility layer the gizmo will be added to
*/
function Gizmo(
/** The utility layer the gizmo will be added to */
gizmoLayer) {
var _this = this;
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_2__["UtilityLayerRenderer"].DefaultUtilityLayer; }
this.gizmoLayer = gizmoLayer;
this._attachedMesh = null;
this._attachedNode = null;
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
this._scaleRatio = 1;
/**
* If a custom mesh has been set (Default: false)
*/
this._customMeshSet = false;
this._updateGizmoRotationToMatchAttachedMesh = true;
/**
* If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
*/
this.updateGizmoPositionToMatchAttachedMesh = true;
/**
* When set, the gizmo will always appear the same size no matter where the camera is (default: true)
*/
this.updateScale = true;
this._interactionsEnabled = true;
this._tempQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"](0, 0, 0, 1);
this._tempVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
this._tempVector2 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"]();
this._tempMatrix1 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"]();
this._tempMatrix2 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"]();
this._rightHandtoLeftHandMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Matrix"].RotationY(Math.PI);
this._rootMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_1__["Mesh"]("gizmoRootNode", gizmoLayer.utilityLayerScene);
this._rootMesh.rotationQuaternion = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity();
this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
_this._update();
});
}
Object.defineProperty(Gizmo.prototype, "scaleRatio", {
get: function () {
return this._scaleRatio;
},
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
set: function (value) {
this._scaleRatio = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(Gizmo.prototype, "attachedMesh", {
/**
* Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
* * When set, interactions will be enabled
*/
get: function () {
return this._attachedMesh;
},
set: function (value) {
this._attachedMesh = value;
if (value) {
this._attachedNode = value;
}
this._rootMesh.setEnabled(value ? true : false);
this._attachedNodeChanged(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Gizmo.prototype, "attachedNode", {
/**
* Node that the gizmo will be attached to. (eg. on a drag gizmo the mesh, bone or NodeTransform that will be dragged)
* * When set, interactions will be enabled
*/
get: function () {
return this._attachedNode;
},
set: function (value) {
this._attachedNode = value;
this._attachedMesh = null;
this._rootMesh.setEnabled(value ? true : false);
this._attachedNodeChanged(value);
},
enumerable: false,
configurable: true
});
/**
* Disposes and replaces the current meshes in the gizmo with the specified mesh
* @param mesh The mesh to replace the default mesh of the gizmo
*/
Gizmo.prototype.setCustomMesh = function (mesh) {
if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
}
this._rootMesh.getChildMeshes().forEach(function (c) {
c.dispose();
});
mesh.parent = this._rootMesh;
this._customMeshSet = true;
};
Object.defineProperty(Gizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
get: function () {
return this._updateGizmoRotationToMatchAttachedMesh;
},
/**
* If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
*/
set: function (value) {
this._updateGizmoRotationToMatchAttachedMesh = value;
},
enumerable: false,
configurable: true
});
Gizmo.prototype._attachedNodeChanged = function (value) {
};
/**
* Updates the gizmo to match the attached mesh's position/rotation
*/
Gizmo.prototype._update = function () {
if (this.attachedNode) {
var effectiveNode = this.attachedNode;
if (this.attachedMesh) {
effectiveNode = this.attachedMesh._effectiveMesh || this.attachedNode;
}
// Position
if (this.updateGizmoPositionToMatchAttachedMesh) {
var row = effectiveNode.getWorldMatrix().getRow(3);
var position = row ? row.toVector3() : new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 0);
this._rootMesh.position.copyFrom(position);
}
// Rotation
if (this.updateGizmoRotationToMatchAttachedMesh) {
effectiveNode.getWorldMatrix().decompose(undefined, this._rootMesh.rotationQuaternion);
}
else {
this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
}
// Scale
if (this.updateScale) {
var activeCamera = this.gizmoLayer.utilityLayerScene.activeCamera;
var cameraPosition = activeCamera.globalPosition;
if (activeCamera.devicePosition) {
cameraPosition = activeCamera.devicePosition;
}
this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
var dist = this._tempVector.length() * this.scaleRatio;
this._rootMesh.scaling.set(dist, dist, dist);
// Account for handedness, similar to Matrix.decompose
if (effectiveNode._getWorldMatrixDeterminant() < 0) {
this._rootMesh.scaling.y *= -1;
}
}
else {
this._rootMesh.scaling.setAll(this.scaleRatio);
}
}
};
/**
* computes the rotation/scaling/position of the transform once the Node world matrix has changed.
* @param value Node, TransformNode or mesh
*/
Gizmo.prototype._matrixChanged = function () {
if (!this._attachedNode) {
return;
}
if (this._attachedNode._isCamera) {
var camera = this._attachedNode;
var worldMatrix;
var worldMatrixUC;
if (camera.parent) {
var parentInv = this._tempMatrix2;
camera.parent._worldMatrix.invertToRef(parentInv);
this._attachedNode._worldMatrix.multiplyToRef(parentInv, this._tempMatrix1);
worldMatrix = this._tempMatrix1;
}
else {
worldMatrix = this._attachedNode._worldMatrix;
}
if (camera.getScene().useRightHandedSystem) {
// avoid desync with RH matrix computation. Otherwise, rotation of PI around Y axis happens each frame resulting in axis flipped because worldMatrix is computed as inverse of viewMatrix.
this._rightHandtoLeftHandMatrix.multiplyToRef(worldMatrix, this._tempMatrix2);
worldMatrixUC = this._tempMatrix2;
}
else {
worldMatrixUC = worldMatrix;
}
worldMatrixUC.decompose(this._tempVector2, this._tempQuaternion, this._tempVector);
var inheritsTargetCamera = this._attachedNode.getClassName() === "FreeCamera"
|| this._attachedNode.getClassName() === "FlyCamera"
|| this._attachedNode.getClassName() === "ArcFollowCamera"
|| this._attachedNode.getClassName() === "TargetCamera"
|| this._attachedNode.getClassName() === "TouchCamera"
|| this._attachedNode.getClassName() === "UniversalCamera";
if (inheritsTargetCamera) {
var targetCamera = this._attachedNode;
targetCamera.rotation = this._tempQuaternion.toEulerAngles();
if (targetCamera.rotationQuaternion) {
targetCamera.rotationQuaternion.copyFrom(this._tempQuaternion);
}
}
camera.position.copyFrom(this._tempVector);
}
else if (this._attachedNode._isMesh || this._attachedNode.getClassName() === "AbstractMesh" || this._attachedNode.getClassName() === "TransformNode" || this._attachedNode.getClassName() === "InstancedMesh") {
var transform = this._attachedNode;
if (transform.parent) {
var parentInv = this._tempMatrix1;
var localMat = this._tempMatrix2;
transform.parent.getWorldMatrix().invertToRef(parentInv);
this._attachedNode._worldMatrix.multiplyToRef(parentInv, localMat);
localMat.decompose(transform.scaling, this._tempQuaternion, transform.position);
}
else {
this._attachedNode._worldMatrix.decompose(transform.scaling, this._tempQuaternion, transform.position);
}
if (transform.rotationQuaternion) {
transform.rotationQuaternion.copyFrom(this._tempQuaternion);
}
else {
transform.rotation = this._tempQuaternion.toEulerAngles();
}
}
else if (this._attachedNode.getClassName() === "Bone") {
var bone = this._attachedNode;
var parent_1 = bone.getParent();
if (parent_1) {
var invParent = this._tempMatrix1;
var boneLocalMatrix = this._tempMatrix2;
parent_1.getWorldMatrix().invertToRef(invParent);
bone.getWorldMatrix().multiplyToRef(invParent, boneLocalMatrix);
var lmat = bone.getLocalMatrix();
lmat.copyFrom(boneLocalMatrix);
bone.markAsDirty();
}
}
};
/**
* Disposes of the gizmo
*/
Gizmo.prototype.dispose = function () {
this._rootMesh.dispose();
if (this._beforeRenderObserver) {
this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
}
};
return Gizmo;
}());
/***/ }),
/***/ "./Gizmos/gizmoManager.ts":
/*!********************************!*\
!*** ./Gizmos/gizmoManager.ts ***!
\********************************/
/*! exports provided: GizmoManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return GizmoManager; });
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Events/pointerEvents */ "./Events/pointerEvents.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Behaviors_Meshes_sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Behaviors/Meshes/sixDofDragBehavior */ "./Behaviors/Meshes/sixDofDragBehavior.ts");
/* harmony import */ var _rotationGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./rotationGizmo */ "./Gizmos/rotationGizmo.ts");
/* harmony import */ var _positionGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./positionGizmo */ "./Gizmos/positionGizmo.ts");
/* harmony import */ var _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scaleGizmo */ "./Gizmos/scaleGizmo.ts");
/* harmony import */ var _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./boundingBoxGizmo */ "./Gizmos/boundingBoxGizmo.ts");
/**
* Helps setup gizmo's in the scene to rotate/scale/position nodes
*/
var GizmoManager = /** @class */ (function () {
/**
* Instatiates a gizmo manager
* @param scene the scene to overlay the gizmos on top of
* @param thickness display gizmo axis thickness
*/
function GizmoManager(scene, thickness) {
var _this = this;
if (thickness === void 0) { thickness = 1; }
this.scene = scene;
/** When true, the gizmo will be detached from the current object when a pointer down occurs with an empty picked mesh */
this.clearGizmoOnEmptyPointerEvent = false;
/** Fires an event when the manager is attached to a mesh */
this.onAttachedToMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/** Fires an event when the manager is attached to a node */
this.onAttachedToNodeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
this._pointerObserver = null;
this._attachedMesh = null;
this._attachedNode = null;
this._boundingBoxColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].FromHexString("#0984e3");
this._thickness = 1;
/**
* When bounding box gizmo is enabled, this can be used to track drag/end events
*/
this.boundingBoxDragBehavior = new _Behaviors_Meshes_sixDofDragBehavior__WEBPACK_IMPORTED_MODULE_5__["SixDofDragBehavior"]();
/**
* Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
*/
this.attachableMeshes = null;
/**
* Array of nodes which will have the gizmo attached when a pointer selected them. If null, all nodes are attachable. (Default: null)
*/
this.attachableNodes = null;
/**
* If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh/attachToNode. (Default: true)
*/
this.usePointerToAttachGizmos = true;
this._defaultKeepDepthUtilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__["UtilityLayerRenderer"](scene);
this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
this._defaultUtilityLayer = new _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_3__["UtilityLayerRenderer"](scene);
this._thickness = thickness;
this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
// Instatiate/dispose gizmos based on pointer actions
this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo) {
if (!_this.usePointerToAttachGizmos) {
return;
}
if (pointerInfo.type == _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_1__["PointerEventTypes"].POINTERDOWN) {
if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
var node = pointerInfo.pickInfo.pickedMesh;
if (_this.attachableMeshes == null) {
// Attach to the most parent node
while (node && node.parent != null) {
node = node.parent;
}
}
else {
// Attach to the parent node that is an attachableMesh
var found = false;
_this.attachableMeshes.forEach(function (mesh) {
if (node && (node == mesh || node.isDescendantOf(mesh))) {
node = mesh;
found = true;
}
});
if (!found) {
node = null;
}
}
if (node instanceof _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"]) {
if (_this._attachedMesh != node) {
_this.attachToMesh(node);
}
}
else {
if (_this.clearGizmoOnEmptyPointerEvent) {
_this.attachToMesh(null);
}
}
}
else {
if (_this.clearGizmoOnEmptyPointerEvent) {
_this.attachToMesh(null);
}
}
}
});
}
Object.defineProperty(GizmoManager.prototype, "keepDepthUtilityLayer", {
/**
* Utility layer that the bounding box gizmo belongs to
*/
get: function () {
return this._defaultKeepDepthUtilityLayer;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GizmoManager.prototype, "utilityLayer", {
/**
* Utility layer that all gizmos besides bounding box belong to
*/
get: function () {
return this._defaultUtilityLayer;
},
enumerable: false,
configurable: true
});
/**
* Attaches a set of gizmos to the specified mesh
* @param mesh The mesh the gizmo's should be attached to
*/
GizmoManager.prototype.attachToMesh = function (mesh) {
if (this._attachedMesh) {
this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
}
if (this._attachedNode) {
this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);
}
this._attachedMesh = mesh;
this._attachedNode = null;
for (var key in this.gizmos) {
var gizmo = (this.gizmos[key]);
if (gizmo && this._gizmosEnabled[key]) {
gizmo.attachedMesh = mesh;
}
}
if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
}
this.onAttachedToMeshObservable.notifyObservers(mesh);
};
/**
* Attaches a set of gizmos to the specified node
* @param node The node the gizmo's should be attached to
*/
GizmoManager.prototype.attachToNode = function (node) {
if (this._attachedMesh) {
this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
}
if (this._attachedNode) {
this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);
}
this._attachedMesh = null;
this._attachedNode = node;
for (var key in this.gizmos) {
var gizmo = (this.gizmos[key]);
if (gizmo && this._gizmosEnabled[key]) {
gizmo.attachedNode = node;
}
}
if (this.boundingBoxGizmoEnabled && this._attachedNode) {
this._attachedNode.addBehavior(this.boundingBoxDragBehavior);
}
this.onAttachedToNodeObservable.notifyObservers(node);
};
Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
get: function () {
return this._gizmosEnabled.positionGizmo;
},
/**
* If the position gizmo is enabled
*/
set: function (value) {
if (value) {
if (!this.gizmos.positionGizmo) {
this.gizmos.positionGizmo = new _positionGizmo__WEBPACK_IMPORTED_MODULE_7__["PositionGizmo"](this._defaultUtilityLayer, this._thickness);
}
if (this._attachedNode) {
this.gizmos.positionGizmo.attachedNode = this._attachedNode;
}
else {
this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
}
}
else if (this.gizmos.positionGizmo) {
this.gizmos.positionGizmo.attachedNode = null;
}
this._gizmosEnabled.positionGizmo = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
get: function () {
return this._gizmosEnabled.rotationGizmo;
},
/**
* If the rotation gizmo is enabled
*/
set: function (value) {
if (value) {
if (!this.gizmos.rotationGizmo) {
this.gizmos.rotationGizmo = new _rotationGizmo__WEBPACK_IMPORTED_MODULE_6__["RotationGizmo"](this._defaultUtilityLayer, 32, false, this._thickness);
}
if (this._attachedNode) {
this.gizmos.rotationGizmo.attachedNode = this._attachedNode;
}
else {
this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
}
}
else if (this.gizmos.rotationGizmo) {
this.gizmos.rotationGizmo.attachedNode = null;
}
this._gizmosEnabled.rotationGizmo = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
get: function () {
return this._gizmosEnabled.scaleGizmo;
},
/**
* If the scale gizmo is enabled
*/
set: function (value) {
if (value) {
this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__["ScaleGizmo"](this._defaultUtilityLayer, this._thickness);
if (this._attachedNode) {
this.gizmos.scaleGizmo.attachedNode = this._attachedNode;
}
else {
this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
}
}
else if (this.gizmos.scaleGizmo) {
this.gizmos.scaleGizmo.attachedNode = null;
}
this._gizmosEnabled.scaleGizmo = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
get: function () {
return this._gizmosEnabled.boundingBoxGizmo;
},
/**
* If the boundingBox gizmo is enabled
*/
set: function (value) {
if (value) {
this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_9__["BoundingBoxGizmo"](this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
if (this._attachedMesh) {
this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
}
else {
this.gizmos.boundingBoxGizmo.attachedNode = this._attachedNode;
}
if (this._attachedMesh) {
this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
}
else if (this._attachedNode) {
this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);
this._attachedNode.addBehavior(this.boundingBoxDragBehavior);
}
}
else if (this.gizmos.boundingBoxGizmo) {
if (this._attachedMesh) {
this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
}
else if (this._attachedNode) {
this._attachedNode.removeBehavior(this.boundingBoxDragBehavior);
}
this.gizmos.boundingBoxGizmo.attachedNode = null;
}
this._gizmosEnabled.boundingBoxGizmo = value;
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo manager
*/
GizmoManager.prototype.dispose = function () {
this.scene.onPointerObservable.remove(this._pointerObserver);
for (var key in this.gizmos) {
var gizmo = (this.gizmos[key]);
if (gizmo) {
gizmo.dispose();
}
}
this._defaultKeepDepthUtilityLayer.dispose();
this._defaultUtilityLayer.dispose();
this.boundingBoxDragBehavior.detach();
this.onAttachedToMeshObservable.clear();
};
return GizmoManager;
}());
/***/ }),
/***/ "./Gizmos/index.ts":
/*!*************************!*\
!*** ./Gizmos/index.ts ***!
\*************************/
/*! exports provided: AxisDragGizmo, AxisScaleGizmo, BoundingBoxGizmo, Gizmo, GizmoManager, PlaneRotationGizmo, PositionGizmo, RotationGizmo, ScaleGizmo, LightGizmo, CameraGizmo, PlaneDragGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _axisDragGizmo__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./axisDragGizmo */ "./Gizmos/axisDragGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return _axisDragGizmo__WEBPACK_IMPORTED_MODULE_0__["AxisDragGizmo"]; });
/* harmony import */ var _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./axisScaleGizmo */ "./Gizmos/axisScaleGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_1__["AxisScaleGizmo"]; });
/* harmony import */ var _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./boundingBoxGizmo */ "./Gizmos/boundingBoxGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return _boundingBoxGizmo__WEBPACK_IMPORTED_MODULE_2__["BoundingBoxGizmo"]; });
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return _gizmo__WEBPACK_IMPORTED_MODULE_3__["Gizmo"]; });
/* harmony import */ var _gizmoManager__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./gizmoManager */ "./Gizmos/gizmoManager.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return _gizmoManager__WEBPACK_IMPORTED_MODULE_4__["GizmoManager"]; });
/* harmony import */ var _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./planeRotationGizmo */ "./Gizmos/planeRotationGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_5__["PlaneRotationGizmo"]; });
/* harmony import */ var _positionGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./positionGizmo */ "./Gizmos/positionGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return _positionGizmo__WEBPACK_IMPORTED_MODULE_6__["PositionGizmo"]; });
/* harmony import */ var _rotationGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./rotationGizmo */ "./Gizmos/rotationGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return _rotationGizmo__WEBPACK_IMPORTED_MODULE_7__["RotationGizmo"]; });
/* harmony import */ var _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./scaleGizmo */ "./Gizmos/scaleGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return _scaleGizmo__WEBPACK_IMPORTED_MODULE_8__["ScaleGizmo"]; });
/* harmony import */ var _lightGizmo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./lightGizmo */ "./Gizmos/lightGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return _lightGizmo__WEBPACK_IMPORTED_MODULE_9__["LightGizmo"]; });
/* harmony import */ var _cameraGizmo__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./cameraGizmo */ "./Gizmos/cameraGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraGizmo", function() { return _cameraGizmo__WEBPACK_IMPORTED_MODULE_10__["CameraGizmo"]; });
/* harmony import */ var _planeDragGizmo__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./planeDragGizmo */ "./Gizmos/planeDragGizmo.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneDragGizmo", function() { return _planeDragGizmo__WEBPACK_IMPORTED_MODULE_11__["PlaneDragGizmo"]; });
/***/ }),
/***/ "./Gizmos/lightGizmo.ts":
/*!******************************!*\
!*** ./Gizmos/lightGizmo.ts ***!
\******************************/
/*! exports provided: LightGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return LightGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts");
/* harmony import */ var _Lights_directionalLight__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Lights/directionalLight */ "./Lights/directionalLight.ts");
/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts");
/* harmony import */ var _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Meshes/Builders/hemisphereBuilder */ "./Meshes/Builders/hemisphereBuilder.ts");
/* harmony import */ var _Lights_spotLight__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Lights/spotLight */ "./Lights/spotLight.ts");
/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts");
/**
* Gizmo that enables viewing a light
*/
var LightGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LightGizmo, _super);
/**
* Creates a LightGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
*/
function LightGizmo(gizmoLayer) {
var _this = _super.call(this, gizmoLayer) || this;
_this._cachedPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]();
_this._cachedForward = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 1);
_this._light = null;
_this.attachedMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_3__["AbstractMesh"]("", _this.gizmoLayer.utilityLayerScene);
_this._attachedMeshParent = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_12__["TransformNode"]("parent", _this.gizmoLayer.utilityLayerScene);
_this.attachedMesh.parent = _this._attachedMeshParent;
_this._material = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_6__["StandardMaterial"]("light", _this.gizmoLayer.utilityLayerScene);
_this._material.diffuseColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.5, 0.5, 0.5);
_this._material.specularColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"](0.1, 0.1, 0.1);
return _this;
}
Object.defineProperty(LightGizmo.prototype, "light", {
get: function () {
return this._light;
},
/**
* The light that the gizmo is attached to
*/
set: function (light) {
var _this = this;
this._light = light;
if (light) {
// Create the mesh for the given light type
if (this._lightMesh) {
this._lightMesh.dispose();
}
if (light instanceof _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__["HemisphericLight"]) {
this._lightMesh = LightGizmo._CreateHemisphericLightMesh(this.gizmoLayer.utilityLayerScene);
}
else if (light instanceof _Lights_directionalLight__WEBPACK_IMPORTED_MODULE_8__["DirectionalLight"]) {
this._lightMesh = LightGizmo._CreateDirectionalLightMesh(this.gizmoLayer.utilityLayerScene);
}
else if (light instanceof _Lights_spotLight__WEBPACK_IMPORTED_MODULE_11__["SpotLight"]) {
this._lightMesh = LightGizmo._CreateSpotLightMesh(this.gizmoLayer.utilityLayerScene);
}
else {
this._lightMesh = LightGizmo._CreatePointLightMesh(this.gizmoLayer.utilityLayerScene);
}
this._lightMesh.getChildMeshes(false).forEach(function (m) {
m.material = _this._material;
});
this._lightMesh.parent = this._rootMesh;
// Add lighting to the light gizmo
var gizmoLight = this.gizmoLayer._getSharedGizmoLight();
gizmoLight.includedOnlyMeshes = gizmoLight.includedOnlyMeshes.concat(this._lightMesh.getChildMeshes(false));
this._lightMesh.rotationQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Quaternion"]();
if (!this.attachedMesh.reservedDataStore) {
this.attachedMesh.reservedDataStore = {};
}
this.attachedMesh.reservedDataStore.lightGizmo = this;
if (light.parent) {
this._attachedMeshParent.freezeWorldMatrix(light.parent.getWorldMatrix());
}
// Get update position and direction if the light has it
if (light.position) {
this.attachedMesh.position.copyFrom(light.position);
this.attachedMesh.computeWorldMatrix(true);
this._cachedPosition.copyFrom(this.attachedMesh.position);
}
if (light.direction) {
this.attachedMesh.setDirection(light.direction);
this.attachedMesh.computeWorldMatrix(true);
this._cachedForward.copyFrom(this.attachedMesh.forward);
}
this._update();
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightGizmo.prototype, "material", {
/**
* Gets the material used to render the light gizmo
*/
get: function () {
return this._material;
},
enumerable: false,
configurable: true
});
/**
* @hidden
* Updates the gizmo to match the attached mesh's position/rotation
*/
LightGizmo.prototype._update = function () {
_super.prototype._update.call(this);
if (!this._light) {
return;
}
if (this._light.parent) {
this._attachedMeshParent.freezeWorldMatrix(this._light.parent.getWorldMatrix());
}
if (this._light.position) {
// If the gizmo is moved update the light otherwise update the gizmo to match the light
if (!this.attachedMesh.position.equals(this._cachedPosition)) {
// update light to match gizmo
this._light.position.copyFrom(this.attachedMesh.position);
this._cachedPosition.copyFrom(this.attachedMesh.position);
}
else {
// update gizmo to match light
this.attachedMesh.position.copyFrom(this._light.position);
this.attachedMesh.computeWorldMatrix(true);
this._cachedPosition.copyFrom(this.attachedMesh.position);
}
}
if (this._light.direction) {
// If the gizmo is moved update the light otherwise update the gizmo to match the light
if (_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.attachedMesh.forward, this._cachedForward) > 0.0001) {
// update light to match gizmo
this._light.direction.copyFrom(this.attachedMesh.forward);
this._cachedForward.copyFrom(this.attachedMesh.forward);
}
else if (_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].DistanceSquared(this.attachedMesh.forward, this._light.direction) > 0.0001) {
// update gizmo to match light
this.attachedMesh.setDirection(this._light.direction);
this.attachedMesh.computeWorldMatrix(true);
this._cachedForward.copyFrom(this.attachedMesh.forward);
}
}
};
/**
* Disposes of the light gizmo
*/
LightGizmo.prototype.dispose = function () {
this._material.dispose();
_super.prototype.dispose.call(this);
this._attachedMeshParent.dispose();
};
LightGizmo._CreateHemisphericLightMesh = function (scene) {
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("hemisphereLight", scene);
var hemisphere = _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_10__["HemisphereBuilder"].CreateHemisphere(root.name, { segments: 10, diameter: 1 }, scene);
hemisphere.position.z = -0.15;
hemisphere.rotation.x = Math.PI / 2;
hemisphere.parent = root;
var lines = this._CreateLightLines(3, scene);
lines.parent = root;
lines.position.z - 0.15;
root.scaling.scaleInPlace(LightGizmo._Scale);
root.rotation.x = Math.PI / 2;
return root;
};
LightGizmo._CreatePointLightMesh = function (scene) {
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("pointLight", scene);
var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_9__["SphereBuilder"].CreateSphere(root.name, { segments: 10, diameter: 1 }, scene);
sphere.rotation.x = Math.PI / 2;
sphere.parent = root;
var lines = this._CreateLightLines(5, scene);
lines.parent = root;
root.scaling.scaleInPlace(LightGizmo._Scale);
root.rotation.x = Math.PI / 2;
return root;
};
LightGizmo._CreateSpotLightMesh = function (scene) {
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("spotLight", scene);
var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_9__["SphereBuilder"].CreateSphere(root.name, { segments: 10, diameter: 1 }, scene);
sphere.parent = root;
var hemisphere = _Meshes_Builders_hemisphereBuilder__WEBPACK_IMPORTED_MODULE_10__["HemisphereBuilder"].CreateHemisphere(root.name, { segments: 10, diameter: 2 }, scene);
hemisphere.parent = root;
hemisphere.rotation.x = -Math.PI / 2;
var lines = this._CreateLightLines(2, scene);
lines.parent = root;
root.scaling.scaleInPlace(LightGizmo._Scale);
root.rotation.x = Math.PI / 2;
return root;
};
LightGizmo._CreateDirectionalLightMesh = function (scene) {
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("directionalLight", scene);
var mesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"](root.name, scene);
mesh.parent = root;
var sphere = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_9__["SphereBuilder"].CreateSphere(root.name, { diameter: 1.2, segments: 10 }, scene);
sphere.parent = mesh;
var line = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateCylinder(root.name, 6, 0.3, 0.3, 6, 1, scene);
line.parent = mesh;
var left = line.clone(root.name);
left.scaling.y = 0.5;
left.position.x += 1.25;
var right = line.clone(root.name);
right.scaling.y = 0.5;
right.position.x += -1.25;
var arrowHead = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateCylinder(root.name, 1, 0, 0.6, 6, 1, scene);
arrowHead.position.y += 3;
arrowHead.parent = mesh;
var left = arrowHead.clone(root.name);
left.position.y = 1.5;
left.position.x += 1.25;
var right = arrowHead.clone(root.name);
right.position.y = 1.5;
right.position.x += -1.25;
mesh.scaling.scaleInPlace(LightGizmo._Scale);
mesh.rotation.z = Math.PI / 2;
mesh.rotation.y = Math.PI / 2;
return root;
};
// Static helper methods
LightGizmo._Scale = 0.007;
/**
* Creates the lines for a light mesh
*/
LightGizmo._CreateLightLines = function (levels, scene) {
var distFromSphere = 1.2;
var root = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("root", scene);
root.rotation.x = Math.PI / 2;
// Create the top line, this will be cloned for all other lines
var linePivot = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"]("linePivot", scene);
linePivot.parent = root;
var line = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].CreateCylinder("line", 2, 0.2, 0.3, 6, 1, scene);
line.position.y = line.scaling.y / 2 + distFromSphere;
line.parent = linePivot;
if (levels < 2) {
return linePivot;
}
for (var i = 0; i < 4; i++) {
var l = linePivot.clone("lineParentClone");
l.rotation.z = Math.PI / 4;
l.rotation.y = (Math.PI / 2) + (Math.PI / 2 * i);
l.getChildMeshes()[0].scaling.y = 0.5;
l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8;
l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere;
}
if (levels < 3) {
return root;
}
for (var i = 0; i < 4; i++) {
var l = linePivot.clone("linePivotClone");
l.rotation.z = Math.PI / 2;
l.rotation.y = (Math.PI / 2 * i);
}
if (levels < 4) {
return root;
}
for (var i = 0; i < 4; i++) {
var l = linePivot.clone("linePivotClone");
l.rotation.z = Math.PI + (Math.PI / 4);
l.rotation.y = (Math.PI / 2) + (Math.PI / 2 * i);
l.getChildMeshes()[0].scaling.y = 0.5;
l.getChildMeshes()[0].scaling.x = l.getChildMeshes()[0].scaling.z = 0.8;
l.getChildMeshes()[0].position.y = l.getChildMeshes()[0].scaling.y / 2 + distFromSphere;
}
if (levels < 5) {
return root;
}
var l = linePivot.clone("linePivotClone");
l.rotation.z = Math.PI;
return root;
};
return LightGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_5__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/planeDragGizmo.ts":
/*!**********************************!*\
!*** ./Gizmos/planeDragGizmo.ts ***!
\**********************************/
/*! exports provided: PlaneDragGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneDragGizmo", function() { return PlaneDragGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts");
/* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts");
/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/**
* Single plane drag gizmo
*/
var PlaneDragGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PlaneDragGizmo, _super);
/**
* Creates a PlaneDragGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param dragPlaneNormal The axis normal to which the gizmo will be able to drag on
* @param color The color of the gizmo
*/
function PlaneDragGizmo(dragPlaneNormal, color, gizmoLayer, parent) {
if (color === void 0) { color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].Gray(); }
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (parent === void 0) { parent = null; }
var _this = _super.call(this, gizmoLayer) || this;
_this._pointerObserver = null;
/**
* Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
*/
_this.snapDistance = 0;
/**
* Event that fires each time the gizmo snaps to a new location.
* * snapDistance is the the change in distance
*/
_this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this._isEnabled = false;
_this._parent = null;
_this._parent = parent;
// Create Material
_this._coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_9__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this._coloredMaterial.diffuseColor = color;
_this._coloredMaterial.specularColor = color.subtract(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.1, 0.1, 0.1));
_this._hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_9__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
_this._hoverMaterial.diffuseColor = color.add(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.3, 0.3, 0.3));
// Build plane mesh on root node
_this._plane = PlaneDragGizmo._CreatePlane(gizmoLayer.utilityLayerScene, _this._coloredMaterial);
_this._plane.lookAt(_this._rootMesh.position.add(dragPlaneNormal));
_this._plane.scaling.scaleInPlace(1 / 3);
_this._plane.parent = _this._rootMesh;
var currentSnapDragDistance = 0;
var tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var tmpSnapEvent = { snapDistance: 0 };
// Add dragPlaneNormal drag behavior to handle events when the gizmo is dragged
_this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_6__["PointerDragBehavior"]({ dragPlaneNormal: dragPlaneNormal });
_this.dragBehavior.moveAttached = false;
_this._rootMesh.addBehavior(_this.dragBehavior);
var localDelta = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"]();
_this.dragBehavior.onDragObservable.add(function (event) {
if (_this.attachedNode) {
// Convert delta to local translation if it has a parent
if (_this.attachedNode.parent) {
_this.attachedNode.parent.computeWorldMatrix().invertToRef(tmpMatrix);
tmpMatrix.setTranslationFromFloats(0, 0, 0);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
}
else {
localDelta.copyFrom(event.delta);
}
// Snapping logic
if (_this.snapDistance == 0) {
_this.attachedNode.getWorldMatrix().addTranslationFromFloats(localDelta.x, localDelta.y, localDelta.z);
}
else {
currentSnapDragDistance += event.dragDistance;
if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
localDelta.normalizeToRef(tmpVector);
tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
_this.attachedNode.getWorldMatrix().addTranslationFromFloats(tmpVector.x, tmpVector.y, tmpVector.z);
tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
_this.onSnapObservable.notifyObservers(tmpSnapEvent);
}
}
_this._matrixChanged();
}
});
_this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) {
if (_this._customMeshSet) {
return;
}
var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
var material = isHovered ? _this._hoverMaterial : _this._coloredMaterial;
_this._rootMesh.getChildMeshes().forEach(function (m) {
m.material = material;
});
});
var light = gizmoLayer._getSharedGizmoLight();
light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false));
return _this;
}
/** @hidden */
PlaneDragGizmo._CreatePlane = function (scene, material) {
var plane = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_4__["TransformNode"]("plane", scene);
//make sure plane is double sided
var dragPlane = _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_5__["PlaneBuilder"].CreatePlane("dragPlane", { width: .1375, height: .1375, sideOrientation: 2 }, scene);
dragPlane.material = material;
dragPlane.parent = plane;
return plane;
};
/** @hidden */
PlaneDragGizmo._CreateArrowInstance = function (scene, arrow) {
var instance = new _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_4__["TransformNode"]("arrow", scene);
for (var _i = 0, _a = arrow.getChildMeshes(); _i < _a.length; _i++) {
var mesh = _a[_i];
var childInstance = mesh.createInstance(mesh.name);
childInstance.parent = instance;
}
return instance;
};
PlaneDragGizmo.prototype._attachedNodeChanged = function (value) {
if (this.dragBehavior) {
this.dragBehavior.enabled = value ? true : false;
}
};
Object.defineProperty(PlaneDragGizmo.prototype, "isEnabled", {
get: function () {
return this._isEnabled;
},
/**
* If the gizmo is enabled
*/
set: function (value) {
this._isEnabled = value;
if (!value) {
this.attachedNode = null;
}
else {
if (this._parent) {
this.attachedNode = this._parent.attachedNode;
}
}
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
PlaneDragGizmo.prototype.dispose = function () {
this.onSnapObservable.clear();
this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
this.dragBehavior.detach();
_super.prototype.dispose.call(this);
if (this._plane) {
this._plane.dispose();
}
[this._coloredMaterial, this._hoverMaterial].forEach(function (matl) {
if (matl) {
matl.dispose();
}
});
};
return PlaneDragGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_7__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/planeRotationGizmo.ts":
/*!**************************************!*\
!*** ./Gizmos/planeRotationGizmo.ts ***!
\**************************************/
/*! exports provided: PlaneRotationGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return PlaneRotationGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Behaviors/Meshes/pointerDragBehavior */ "./Behaviors/Meshes/pointerDragBehavior.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Meshes_Builders_linesBuilder__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Meshes/Builders/linesBuilder */ "./Meshes/Builders/linesBuilder.ts");
/**
* Single plane rotation gizmo
*/
var PlaneRotationGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PlaneRotationGizmo, _super);
/**
* Creates a PlaneRotationGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param planeNormal The normal of the plane which the gizmo will be able to rotate on
* @param color The color of the gizmo
* @param tessellation Amount of tessellation to be used when creating rotation circles
* @param useEulerRotation Use and update Euler angle instead of quaternion
* @param thickness display gizmo axis thickness
*/
function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation, parent, useEulerRotation, thickness) {
if (color === void 0) { color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].Gray(); }
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (tessellation === void 0) { tessellation = 32; }
if (parent === void 0) { parent = null; }
if (useEulerRotation === void 0) { useEulerRotation = false; }
if (thickness === void 0) { thickness = 1; }
var _this = _super.call(this, gizmoLayer) || this;
_this._pointerObserver = null;
/**
* Rotation distance in radians that the gizmo will snap to (Default: 0)
*/
_this.snapDistance = 0;
/**
* Event that fires each time the gizmo snaps to a new location.
* * snapDistance is the the change in distance
*/
_this.onSnapObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
_this._isEnabled = true;
_this._parent = null;
_this._parent = parent;
// Create Material
var coloredMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_9__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
coloredMaterial.diffuseColor = color;
coloredMaterial.specularColor = color.subtract(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.1, 0.1, 0.1));
var hoverMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_9__["StandardMaterial"]("", gizmoLayer.utilityLayerScene);
hoverMaterial.diffuseColor = color.add(new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.3, 0.3, 0.3));
// Build mesh on root node
var parentMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_4__["AbstractMesh"]("", gizmoLayer.utilityLayerScene);
var drag = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreateTorus("", 0.6, 0.03 * thickness, tessellation, gizmoLayer.utilityLayerScene);
drag.visibility = 0;
var rotationMesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreateTorus("", 0.6, 0.005 * thickness, tessellation, gizmoLayer.utilityLayerScene);
rotationMesh.material = coloredMaterial;
// Position arrow pointing in its drag axis
rotationMesh.rotation.x = Math.PI / 2;
drag.rotation.x = Math.PI / 2;
parentMesh.addChild(rotationMesh);
parentMesh.addChild(drag);
parentMesh.lookAt(_this._rootMesh.position.add(planeNormal));
_this._rootMesh.addChild(parentMesh);
parentMesh.scaling.scaleInPlace(1 / 3);
// Add drag behavior to handle events when the gizmo is dragged
_this.dragBehavior = new _Behaviors_Meshes_pointerDragBehavior__WEBPACK_IMPORTED_MODULE_6__["PointerDragBehavior"]({ dragPlaneNormal: planeNormal });
_this.dragBehavior.moveAttached = false;
_this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
_this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
_this._rootMesh.addBehavior(_this.dragBehavior);
var lastDragPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
_this.dragBehavior.onDragStartObservable.add(function (e) {
if (_this.attachedNode) {
lastDragPosition.copyFrom(e.dragPlanePoint);
}
});
var rotationMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"]();
var planeNormalTowardsCamera = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var localPlaneNormalTowardsCamera = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
var tmpSnapEvent = { snapDistance: 0 };
var currentSnapDragDistance = 0;
var tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"]();
var amountToRotate = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"]();
_this.dragBehavior.onDragObservable.add(function (event) {
if (_this.attachedNode) {
// Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
var nodeScale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1, 1, 1);
var nodeQuaternion = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"](0, 0, 0, 1);
var nodeTranslation = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0, 0, 0);
_this.attachedNode.getWorldMatrix().decompose(nodeScale, nodeQuaternion, nodeTranslation);
var newVector = event.dragPlanePoint.subtract(nodeTranslation).normalize();
var originalVector = lastDragPosition.subtract(nodeTranslation).normalize();
var cross = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(newVector, originalVector);
var dot = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(newVector, originalVector);
var angle = Math.atan2(cross.length(), dot);
planeNormalTowardsCamera.copyFrom(planeNormal);
localPlaneNormalTowardsCamera.copyFrom(planeNormal);
if (_this.updateGizmoRotationToMatchAttachedMesh) {
nodeQuaternion.toRotationMatrix(rotationMatrix);
localPlaneNormalTowardsCamera = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
}
// Flip up vector depending on which side the camera is on
if (gizmoLayer.utilityLayerScene.activeCamera) {
var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(nodeTranslation);
if (_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
planeNormalTowardsCamera.scaleInPlace(-1);
localPlaneNormalTowardsCamera.scaleInPlace(-1);
}
}
var halfCircleSide = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
if (halfCircleSide) {
angle = -angle;
}
// Snapping logic
var snapped = false;
if (_this.snapDistance != 0) {
currentSnapDragDistance += angle;
if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
if (currentSnapDragDistance < 0) {
dragSteps *= -1;
}
currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
angle = _this.snapDistance * dragSteps;
snapped = true;
}
else {
angle = 0;
}
}
// Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
var quaternionCoefficient = Math.sin(angle / 2);
amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
// If the meshes local scale is inverted (eg. loaded gltf file parent with z scale of -1) the rotation needs to be inverted on the y axis
if (tmpMatrix.determinant() > 0) {
var tmpVector = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"]();
amountToRotate.toEulerAnglesToRef(tmpVector);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Quaternion"].RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
}
if (_this.updateGizmoRotationToMatchAttachedMesh) {
// Rotate selected mesh quaternion over fixed axis
nodeQuaternion.multiplyToRef(amountToRotate, nodeQuaternion);
}
else {
// Rotate selected mesh quaternion over rotated axis
amountToRotate.multiplyToRef(nodeQuaternion, nodeQuaternion);
}
// recompose matrix
_this.attachedNode.getWorldMatrix().copyFrom(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Compose(nodeScale, nodeQuaternion, nodeTranslation));
lastDragPosition.copyFrom(event.dragPlanePoint);
if (snapped) {
tmpSnapEvent.snapDistance = angle;
_this.onSnapObservable.notifyObservers(tmpSnapEvent);
}
_this._matrixChanged();
}
});
_this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo) {
if (_this._customMeshSet) {
return;
}
var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
var material = isHovered ? hoverMaterial : coloredMaterial;
_this._rootMesh.getChildMeshes().forEach(function (m) {
m.material = material;
if (m.color) {
m.color = material.diffuseColor;
}
});
});
var light = gizmoLayer._getSharedGizmoLight();
light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._rootMesh.getChildMeshes(false));
return _this;
}
PlaneRotationGizmo.prototype._attachedNodeChanged = function (value) {
if (this.dragBehavior) {
this.dragBehavior.enabled = value ? true : false;
}
};
Object.defineProperty(PlaneRotationGizmo.prototype, "isEnabled", {
get: function () {
return this._isEnabled;
},
/**
* If the gizmo is enabled
*/
set: function (value) {
this._isEnabled = value;
if (!value) {
this.attachedMesh = null;
}
else {
if (this._parent) {
this.attachedMesh = this._parent.attachedMesh;
}
}
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
PlaneRotationGizmo.prototype.dispose = function () {
this.onSnapObservable.clear();
this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
this.dragBehavior.detach();
_super.prototype.dispose.call(this);
};
return PlaneRotationGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_7__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/positionGizmo.ts":
/*!*********************************!*\
!*** ./Gizmos/positionGizmo.ts ***!
\*********************************/
/*! exports provided: PositionGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return PositionGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _axisDragGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./axisDragGizmo */ "./Gizmos/axisDragGizmo.ts");
/* harmony import */ var _planeDragGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./planeDragGizmo */ "./Gizmos/planeDragGizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/**
* Gizmo that enables dragging a mesh along 3 axis
*/
var PositionGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PositionGizmo, _super);
/**
* Creates a PositionGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
@param thickness display gizmo axis thickness
*/
function PositionGizmo(gizmoLayer, thickness) {
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (thickness === void 0) { thickness = 1; }
var _this = _super.call(this, gizmoLayer) || this;
/**
* private variables
*/
_this._meshAttached = null;
_this._nodeAttached = null;
/** Fires an event when any of it's sub gizmos are dragged */
_this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/** Fires an event when any of it's sub gizmos are released from dragging */
_this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* If set to true, planar drag is enabled
*/
_this._planarGizmoEnabled = false;
_this.xGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisDragGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Red().scale(0.5), gizmoLayer, _this, thickness);
_this.yGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisDragGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Green().scale(0.5), gizmoLayer, _this, thickness);
_this.zGizmo = new _axisDragGizmo__WEBPACK_IMPORTED_MODULE_6__["AxisDragGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Blue().scale(0.5), gizmoLayer, _this, thickness);
_this.xPlaneGizmo = new _planeDragGizmo__WEBPACK_IMPORTED_MODULE_7__["PlaneDragGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Red().scale(0.5), _this.gizmoLayer, _this);
_this.yPlaneGizmo = new _planeDragGizmo__WEBPACK_IMPORTED_MODULE_7__["PlaneDragGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Green().scale(0.5), _this.gizmoLayer, _this);
_this.zPlaneGizmo = new _planeDragGizmo__WEBPACK_IMPORTED_MODULE_7__["PlaneDragGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Blue().scale(0.5), _this.gizmoLayer, _this);
// Relay drag events
[_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.xPlaneGizmo, _this.yPlaneGizmo, _this.zPlaneGizmo].forEach(function (gizmo) {
gizmo.dragBehavior.onDragStartObservable.add(function () {
_this.onDragStartObservable.notifyObservers({});
});
gizmo.dragBehavior.onDragEndObservable.add(function () {
_this.onDragEndObservable.notifyObservers({});
});
});
_this.attachedMesh = null;
return _this;
}
Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
get: function () {
return this._meshAttached;
},
set: function (mesh) {
this._meshAttached = mesh;
this._nodeAttached = mesh;
[this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo.isEnabled) {
gizmo.attachedMesh = mesh;
}
else {
gizmo.attachedMesh = null;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(PositionGizmo.prototype, "attachedNode", {
get: function () {
return this._nodeAttached;
},
set: function (node) {
this._meshAttached = null;
this._nodeAttached = null;
[this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo.isEnabled) {
gizmo.attachedNode = node;
}
else {
gizmo.attachedNode = null;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(PositionGizmo.prototype, "planarGizmoEnabled", {
get: function () {
return this._planarGizmoEnabled;
},
/**
* If the planar drag gizmo is enabled
* setting this will enable/disable XY, XZ and YZ planes regardless of individual gizmo settings.
*/
set: function (value) {
var _this = this;
this._planarGizmoEnabled = value;
[this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.isEnabled = value;
if (value) {
if (gizmo.attachedMesh) {
gizmo.attachedMesh = _this.attachedMesh;
}
else {
gizmo.attachedNode = _this.attachedNode;
}
}
}
}, this);
},
enumerable: false,
configurable: true
});
Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
get: function () {
return this._updateGizmoRotationToMatchAttachedMesh;
},
set: function (value) {
this._updateGizmoRotationToMatchAttachedMesh = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.updateGizmoRotationToMatchAttachedMesh = value;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
get: function () {
return this._snapDistance;
},
/**
* Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
*/
set: function (value) {
this._snapDistance = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.snapDistance = value;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
get: function () {
return this._scaleRatio;
},
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
set: function (value) {
this._scaleRatio = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.scaleRatio = value;
}
});
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
PositionGizmo.prototype.dispose = function () {
[this.xGizmo, this.yGizmo, this.zGizmo, this.xPlaneGizmo, this.yPlaneGizmo, this.zPlaneGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.dispose();
}
});
this.onDragStartObservable.clear();
this.onDragEndObservable.clear();
};
/**
* CustomMeshes are not supported by this gizmo
* @param mesh The mesh to replace the default mesh of the gizmo
*/
PositionGizmo.prototype.setCustomMesh = function (mesh) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo,gizmo.xPlaneGizmo, gizmo.yPlaneGizmo, gizmo.zPlaneGizmo)");
};
return PositionGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_5__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/rotationGizmo.ts":
/*!*********************************!*\
!*** ./Gizmos/rotationGizmo.ts ***!
\*********************************/
/*! exports provided: RotationGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return RotationGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./planeRotationGizmo */ "./Gizmos/planeRotationGizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/**
* Gizmo that enables rotating a mesh along 3 axis
*/
var RotationGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RotationGizmo, _super);
/**
* Creates a RotationGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param tessellation Amount of tessellation to be used when creating rotation circles
* @param useEulerRotation Use and update Euler angle instead of quaternion
* @param thickness display gizmo axis thickness
*/
function RotationGizmo(gizmoLayer, tessellation, useEulerRotation, thickness) {
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_7__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (tessellation === void 0) { tessellation = 32; }
if (useEulerRotation === void 0) { useEulerRotation = false; }
if (thickness === void 0) { thickness = 1; }
var _this = _super.call(this, gizmoLayer) || this;
/** Fires an event when any of it's sub gizmos are dragged */
_this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/** Fires an event when any of it's sub gizmos are released from dragging */
_this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
_this.xGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_6__["PlaneRotationGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Red().scale(0.5), gizmoLayer, tessellation, _this, useEulerRotation, thickness);
_this.yGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_6__["PlaneRotationGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Green().scale(0.5), gizmoLayer, tessellation, _this, useEulerRotation, thickness);
_this.zGizmo = new _planeRotationGizmo__WEBPACK_IMPORTED_MODULE_6__["PlaneRotationGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Blue().scale(0.5), gizmoLayer, tessellation, _this, useEulerRotation, thickness);
// Relay drag events
[_this.xGizmo, _this.yGizmo, _this.zGizmo].forEach(function (gizmo) {
gizmo.dragBehavior.onDragStartObservable.add(function () {
_this.onDragStartObservable.notifyObservers({});
});
gizmo.dragBehavior.onDragEndObservable.add(function () {
_this.onDragEndObservable.notifyObservers({});
});
});
_this.attachedMesh = null;
_this.attachedNode = null;
return _this;
}
Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
get: function () {
return this._meshAttached;
},
set: function (mesh) {
this._meshAttached = mesh;
this._nodeAttached = mesh;
[this.xGizmo, this.yGizmo, this.zGizmo].forEach(function (gizmo) {
if (gizmo.isEnabled) {
gizmo.attachedMesh = mesh;
}
else {
gizmo.attachedMesh = null;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(RotationGizmo.prototype, "attachedNode", {
get: function () {
return this._nodeAttached;
},
set: function (node) {
this._meshAttached = null;
this._nodeAttached = node;
[this.xGizmo, this.yGizmo, this.zGizmo].forEach(function (gizmo) {
if (gizmo.isEnabled) {
gizmo.attachedNode = node;
}
else {
gizmo.attachedNode = null;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
get: function () {
return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
},
set: function (value) {
if (this.xGizmo) {
this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
get: function () {
return this.xGizmo.snapDistance;
},
/**
* Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
*/
set: function (value) {
if (this.xGizmo) {
this.xGizmo.snapDistance = value;
this.yGizmo.snapDistance = value;
this.zGizmo.snapDistance = value;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
get: function () {
return this.xGizmo.scaleRatio;
},
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
set: function (value) {
if (this.xGizmo) {
this.xGizmo.scaleRatio = value;
this.yGizmo.scaleRatio = value;
this.zGizmo.scaleRatio = value;
}
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
RotationGizmo.prototype.dispose = function () {
this.xGizmo.dispose();
this.yGizmo.dispose();
this.zGizmo.dispose();
this.onDragStartObservable.clear();
this.onDragEndObservable.clear();
};
/**
* CustomMeshes are not supported by this gizmo
* @param mesh The mesh to replace the default mesh of the gizmo
*/
RotationGizmo.prototype.setCustomMesh = function (mesh) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Error("Custom meshes are not supported on this gizmo, please set the custom meshes on the gizmos contained within this one (gizmo.xGizmo, gizmo.yGizmo, gizmo.zGizmo)");
};
return RotationGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_5__["Gizmo"]));
/***/ }),
/***/ "./Gizmos/scaleGizmo.ts":
/*!******************************!*\
!*** ./Gizmos/scaleGizmo.ts ***!
\******************************/
/*! exports provided: ScaleGizmo */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return ScaleGizmo; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/Builders/polyhedronBuilder */ "./Meshes/Builders/polyhedronBuilder.ts");
/* harmony import */ var _gizmo__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./gizmo */ "./Gizmos/gizmo.ts");
/* harmony import */ var _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./axisScaleGizmo */ "./Gizmos/axisScaleGizmo.ts");
/* harmony import */ var _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Rendering/utilityLayerRenderer */ "./Rendering/utilityLayerRenderer.ts");
/**
* Gizmo that enables scaling a mesh along 3 axis
*/
var ScaleGizmo = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ScaleGizmo, _super);
/**
* Creates a ScaleGizmo
* @param gizmoLayer The utility layer the gizmo will be added to
* @param thickness display gizmo axis thickness
*/
function ScaleGizmo(gizmoLayer, thickness) {
if (gizmoLayer === void 0) { gizmoLayer = _Rendering_utilityLayerRenderer__WEBPACK_IMPORTED_MODULE_8__["UtilityLayerRenderer"].DefaultUtilityLayer; }
if (thickness === void 0) { thickness = 1; }
var _this = _super.call(this, gizmoLayer) || this;
_this._meshAttached = null;
_this._nodeAttached = null;
_this._sensitivity = 1;
/** Fires an event when any of it's sub gizmos are dragged */
_this.onDragStartObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/** Fires an event when any of it's sub gizmos are released from dragging */
_this.onDragEndObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
_this.xGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_7__["AxisScaleGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](1, 0, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Red().scale(0.5), gizmoLayer, _this, thickness);
_this.yGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_7__["AxisScaleGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Green().scale(0.5), gizmoLayer, _this, thickness);
_this.zGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_7__["AxisScaleGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 0, 1), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Blue().scale(0.5), gizmoLayer, _this, thickness);
// Create uniform scale gizmo
_this.uniformScaleGizmo = new _axisScaleGizmo__WEBPACK_IMPORTED_MODULE_7__["AxisScaleGizmo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"](0, 1, 0), _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"].Yellow().scale(0.5), gizmoLayer, _this);
_this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
_this.uniformScaleGizmo.uniformScaling = true;
_this._uniformScalingMesh = _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_5__["PolyhedronBuilder"].CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
_this._uniformScalingMesh.scaling.scaleInPlace(0.02);
_this._uniformScalingMesh.visibility = 0;
_this._octahedron = _Meshes_Builders_polyhedronBuilder__WEBPACK_IMPORTED_MODULE_5__["PolyhedronBuilder"].CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
_this._octahedron.scaling.scaleInPlace(0.007);
_this._uniformScalingMesh.addChild(_this._octahedron);
_this.uniformScaleGizmo.setCustomMesh(_this._uniformScalingMesh, true);
var light = gizmoLayer._getSharedGizmoLight();
light.includedOnlyMeshes = light.includedOnlyMeshes.concat(_this._octahedron);
// Relay drag events
[_this.xGizmo, _this.yGizmo, _this.zGizmo, _this.uniformScaleGizmo].forEach(function (gizmo) {
gizmo.dragBehavior.onDragStartObservable.add(function () {
_this.onDragStartObservable.notifyObservers({});
});
gizmo.dragBehavior.onDragEndObservable.add(function () {
_this.onDragEndObservable.notifyObservers({});
});
});
_this.attachedMesh = null;
_this.attachedNode = null;
return _this;
}
Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
get: function () {
return this._meshAttached;
},
set: function (mesh) {
this._meshAttached = mesh;
this._nodeAttached = mesh;
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo.isEnabled) {
gizmo.attachedMesh = mesh;
}
else {
gizmo.attachedMesh = null;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleGizmo.prototype, "attachedNode", {
get: function () {
return this._nodeAttached;
},
set: function (node) {
this._meshAttached = null;
this._nodeAttached = node;
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo.isEnabled) {
gizmo.attachedNode = node;
}
else {
gizmo.attachedNode = null;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
get: function () {
return this._updateGizmoRotationToMatchAttachedMesh;
},
set: function (value) {
if (!value) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_1__["Logger"].Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
}
else {
this._updateGizmoRotationToMatchAttachedMesh = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.updateGizmoRotationToMatchAttachedMesh = value;
}
});
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
get: function () {
return this._snapDistance;
},
/**
* Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
*/
set: function (value) {
this._snapDistance = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.snapDistance = value;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
get: function () {
return this._scaleRatio;
},
/**
* Ratio for the scale of the gizmo (Default: 1)
*/
set: function (value) {
this._scaleRatio = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.scaleRatio = value;
}
});
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleGizmo.prototype, "sensitivity", {
get: function () {
return this._sensitivity;
},
/**
* Sensitivity factor for dragging (Default: 1)
*/
set: function (value) {
this._sensitivity = value;
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.sensitivity = value;
}
});
},
enumerable: false,
configurable: true
});
/**
* Disposes of the gizmo
*/
ScaleGizmo.prototype.dispose = function () {
[this.xGizmo, this.yGizmo, this.zGizmo, this.uniformScaleGizmo].forEach(function (gizmo) {
if (gizmo) {
gizmo.dispose();
}
});
this.onDragStartObservable.clear();
this.onDragEndObservable.clear();
[this._uniformScalingMesh, this._octahedron].forEach(function (msh) {
if (msh) {
msh.dispose();
}
});
};
return ScaleGizmo;
}(_gizmo__WEBPACK_IMPORTED_MODULE_6__["Gizmo"]));
/***/ }),
/***/ "./Helpers/environmentHelper.ts":
/*!**************************************!*\
!*** ./Helpers/environmentHelper.ts ***!
\**************************************/
/*! exports provided: EnvironmentHelper */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return EnvironmentHelper; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/baseTexture */ "./Materials/Textures/baseTexture.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Textures_mirrorTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/mirrorTexture */ "./Materials/Textures/mirrorTexture.ts");
/* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts");
/* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Meshes_Builders_planeBuilder__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Meshes/Builders/planeBuilder */ "./Meshes/Builders/planeBuilder.ts");
/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts");
/* harmony import */ var _Maths_math_plane__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Maths/math.plane */ "./Maths/math.plane.ts");
/**
* The Environment helper class can be used to add a fully featuread none expensive background to your scene.
* It includes by default a skybox and a ground relying on the BackgroundMaterial.
* It also helps with the default setup of your imageProcessing configuration.
*/
var EnvironmentHelper = /** @class */ (function () {
/**
* constructor
* @param options Defines the options we want to customize the helper
* @param scene The scene to add the material to
*/
function EnvironmentHelper(options, scene) {
var _this = this;
this._errorHandler = function (message, exception) {
_this.onErrorObservable.notifyObservers({ message: message, exception: exception });
};
this._options = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, EnvironmentHelper._getDefaultOptions()), options);
this._scene = scene;
this.onErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
this._setupBackground();
this._setupImageProcessing();
}
/**
* Creates the default options for the helper.
*/
EnvironmentHelper._getDefaultOptions = function () {
return {
createGround: true,
groundSize: 15,
groundTexture: this._groundTextureCDNUrl,
groundColor: new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"](0.2, 0.2, 0.3).toLinearSpace().scale(3),
groundOpacity: 0.9,
enableGroundShadow: true,
groundShadowLevel: 0.5,
enableGroundMirror: false,
groundMirrorSizeRatio: 0.3,
groundMirrorBlurKernel: 64,
groundMirrorAmount: 1,
groundMirrorFresnelWeight: 1,
groundMirrorFallOffDistance: 0,
groundMirrorTextureType: _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].TEXTURETYPE_UNSIGNED_INT,
groundYBias: 0.00001,
createSkybox: true,
skyboxSize: 20,
skyboxTexture: this._skyboxTextureCDNUrl,
skyboxColor: new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color3"](0.2, 0.2, 0.3).toLinearSpace().scale(3),
backgroundYRotation: 0,
sizeAuto: true,
rootPosition: _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector3"].Zero(),
setupImageProcessing: true,
environmentTexture: this._environmentTextureCDNUrl,
cameraExposure: 0.8,
cameraContrast: 1.2,
toneMappingEnabled: true,
};
};
Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
/**
* Gets the root mesh created by the helper.
*/
get: function () {
return this._rootMesh;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
/**
* Gets the skybox created by the helper.
*/
get: function () {
return this._skybox;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
/**
* Gets the skybox texture created by the helper.
*/
get: function () {
return this._skyboxTexture;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
/**
* Gets the skybox material created by the helper.
*/
get: function () {
return this._skyboxMaterial;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "ground", {
/**
* Gets the ground mesh created by the helper.
*/
get: function () {
return this._ground;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
/**
* Gets the ground texture created by the helper.
*/
get: function () {
return this._groundTexture;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
/**
* Gets the ground mirror created by the helper.
*/
get: function () {
return this._groundMirror;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
/**
* Gets the ground mirror render list to helps pushing the meshes
* you wish in the ground reflection.
*/
get: function () {
if (this._groundMirror) {
return this._groundMirror.renderList;
}
return null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
/**
* Gets the ground material created by the helper.
*/
get: function () {
return this._groundMaterial;
},
enumerable: false,
configurable: true
});
/**
* Updates the background according to the new options
* @param options
*/
EnvironmentHelper.prototype.updateOptions = function (options) {
var newOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this._options), options);
if (this._ground && !newOptions.createGround) {
this._ground.dispose();
this._ground = null;
}
if (this._groundMaterial && !newOptions.createGround) {
this._groundMaterial.dispose();
this._groundMaterial = null;
}
if (this._groundTexture) {
if (this._options.groundTexture != newOptions.groundTexture) {
this._groundTexture.dispose();
this._groundTexture = null;
}
}
if (this._skybox && !newOptions.createSkybox) {
this._skybox.dispose();
this._skybox = null;
}
if (this._skyboxMaterial && !newOptions.createSkybox) {
this._skyboxMaterial.dispose();
this._skyboxMaterial = null;
}
if (this._skyboxTexture) {
if (this._options.skyboxTexture != newOptions.skyboxTexture) {
this._skyboxTexture.dispose();
this._skyboxTexture = null;
}
}
if (this._groundMirror && !newOptions.enableGroundMirror) {
this._groundMirror.dispose();
this._groundMirror = null;
}
if (this._scene.environmentTexture) {
if (this._options.environmentTexture != newOptions.environmentTexture) {
this._scene.environmentTexture.dispose();
}
}
this._options = newOptions;
this._setupBackground();
this._setupImageProcessing();
};
/**
* Sets the primary color of all the available elements.
* @param color the main color to affect to the ground and the background
*/
EnvironmentHelper.prototype.setMainColor = function (color) {
if (this.groundMaterial) {
this.groundMaterial.primaryColor = color;
}
if (this.skyboxMaterial) {
this.skyboxMaterial.primaryColor = color;
}
if (this.groundMirror) {
this.groundMirror.clearColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color4"](color.r, color.g, color.b, 1.0);
}
};
/**
* Setup the image processing according to the specified options.
*/
EnvironmentHelper.prototype._setupImageProcessing = function () {
if (this._options.setupImageProcessing) {
this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
this._setupEnvironmentTexture();
}
};
/**
* Setup the environment texture according to the specified options.
*/
EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
if (this._scene.environmentTexture) {
return;
}
if (this._options.environmentTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_6__["BaseTexture"]) {
this._scene.environmentTexture = this._options.environmentTexture;
return;
}
var environmentTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__["CubeTexture"].CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
this._scene.environmentTexture = environmentTexture;
};
/**
* Setup the background according to the specified options.
*/
EnvironmentHelper.prototype._setupBackground = function () {
if (!this._rootMesh) {
this._rootMesh = new _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"]("BackgroundHelper", this._scene);
}
this._rootMesh.rotation.y = this._options.backgroundYRotation;
var sceneSize = this._getSceneSize();
if (this._options.createGround) {
this._setupGround(sceneSize);
this._setupGroundMaterial();
this._setupGroundDiffuseTexture();
if (this._options.enableGroundMirror) {
this._setupGroundMirrorTexture(sceneSize);
}
this._setupMirrorInGroundMaterial();
}
if (this._options.createSkybox) {
this._setupSkybox(sceneSize);
this._setupSkyboxMaterial();
this._setupSkyboxReflectionTexture();
}
this._rootMesh.position.x = sceneSize.rootPosition.x;
this._rootMesh.position.z = sceneSize.rootPosition.z;
this._rootMesh.position.y = sceneSize.rootPosition.y;
};
/**
* Get the scene sizes according to the setup.
*/
EnvironmentHelper.prototype._getSceneSize = function () {
var _this = this;
var groundSize = this._options.groundSize;
var skyboxSize = this._options.skyboxSize;
var rootPosition = this._options.rootPosition;
if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
}
var sceneExtends = this._scene.getWorldExtends(function (mesh) {
return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
});
var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
if (this._options.sizeAuto) {
if (this._scene.activeCamera instanceof _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_2__["ArcRotateCamera"] &&
this._scene.activeCamera.upperRadiusLimit) {
groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
skyboxSize = groundSize;
}
var sceneDiagonalLenght = sceneDiagonal.length();
if (sceneDiagonalLenght > groundSize) {
groundSize = sceneDiagonalLenght * 2;
skyboxSize = groundSize;
}
// 10 % bigger.
groundSize *= 1.1;
skyboxSize *= 1.5;
rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
}
return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
};
/**
* Setup the ground according to the specified options.
*/
EnvironmentHelper.prototype._setupGround = function (sceneSize) {
var _this = this;
if (!this._ground || this._ground.isDisposed()) {
this._ground = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
this._ground.rotation.x = Math.PI / 2; // Face up by default.
this._ground.parent = this._rootMesh;
this._ground.onDisposeObservable.add(function () { _this._ground = null; });
}
this._ground.receiveShadows = this._options.enableGroundShadow;
};
/**
* Setup the ground material according to the specified options.
*/
EnvironmentHelper.prototype._setupGroundMaterial = function () {
if (!this._groundMaterial) {
this._groundMaterial = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_10__["BackgroundMaterial"]("BackgroundPlaneMaterial", this._scene);
}
this._groundMaterial.alpha = this._options.groundOpacity;
this._groundMaterial.alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF;
this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
this._groundMaterial.primaryColor = this._options.groundColor;
this._groundMaterial.useRGBColor = false;
this._groundMaterial.enableNoise = true;
if (this._ground) {
this._ground.material = this._groundMaterial;
}
};
/**
* Setup the ground diffuse texture according to the specified options.
*/
EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
if (!this._groundMaterial) {
return;
}
if (this._groundTexture) {
return;
}
if (this._options.groundTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_6__["BaseTexture"]) {
this._groundMaterial.diffuseTexture = this._options.groundTexture;
return;
}
var diffuseTexture = new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"](this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
diffuseTexture.gammaSpace = false;
diffuseTexture.hasAlpha = true;
this._groundMaterial.diffuseTexture = diffuseTexture;
};
/**
* Setup the ground mirror texture according to the specified options.
*/
EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
var wrapping = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE;
if (!this._groundMirror) {
this._groundMirror = new _Materials_Textures_mirrorTexture__WEBPACK_IMPORTED_MODULE_8__["MirrorTexture"]("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, true);
this._groundMirror.mirrorPlane = new _Maths_math_plane__WEBPACK_IMPORTED_MODULE_14__["Plane"](0, -1, 0, sceneSize.rootPosition.y);
this._groundMirror.anisotropicFilteringLevel = 1;
this._groundMirror.wrapU = wrapping;
this._groundMirror.wrapV = wrapping;
this._groundMirror.gammaSpace = false;
if (this._groundMirror.renderList) {
for (var i = 0; i < this._scene.meshes.length; i++) {
var mesh = this._scene.meshes[i];
if (mesh !== this._ground &&
mesh !== this._skybox &&
mesh !== this._rootMesh) {
this._groundMirror.renderList.push(mesh);
}
}
}
}
this._groundMirror.clearColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color4"](this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
};
/**
* Setup the ground to receive the mirror texture.
*/
EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
if (this._groundMaterial) {
this._groundMaterial.reflectionTexture = this._groundMirror;
this._groundMaterial.reflectionFresnel = true;
this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
}
};
/**
* Setup the skybox according to the specified options.
*/
EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
var _this = this;
if (!this._skybox || this._skybox.isDisposed()) {
this._skybox = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_5__["Mesh"].BACKSIDE);
this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
}
this._skybox.parent = this._rootMesh;
};
/**
* Setup the skybox material according to the specified options.
*/
EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
if (!this._skybox) {
return;
}
if (!this._skyboxMaterial) {
this._skyboxMaterial = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_10__["BackgroundMaterial"]("BackgroundSkyboxMaterial", this._scene);
}
this._skyboxMaterial.useRGBColor = false;
this._skyboxMaterial.primaryColor = this._options.skyboxColor;
this._skyboxMaterial.enableNoise = true;
this._skybox.material = this._skyboxMaterial;
};
/**
* Setup the skybox reflection texture according to the specified options.
*/
EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
if (!this._skyboxMaterial) {
return;
}
if (this._skyboxTexture) {
return;
}
if (this._options.skyboxTexture instanceof _Materials_Textures_baseTexture__WEBPACK_IMPORTED_MODULE_6__["BaseTexture"]) {
this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
return;
}
this._skyboxTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__["CubeTexture"](this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
this._skyboxTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].SKYBOX_MODE;
this._skyboxTexture.gammaSpace = false;
this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
};
/**
* Dispose all the elements created by the Helper.
*/
EnvironmentHelper.prototype.dispose = function () {
if (this._groundMaterial) {
this._groundMaterial.dispose(true, true);
}
if (this._skyboxMaterial) {
this._skyboxMaterial.dispose(true, true);
}
this._rootMesh.dispose(false);
};
/**
* Default ground texture URL.
*/
EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
/**
* Default skybox texture URL.
*/
EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
/**
* Default environment texture URL.
*/
EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
return EnvironmentHelper;
}());
/***/ }),
/***/ "./Helpers/index.ts":
/*!**************************!*\
!*** ./Helpers/index.ts ***!
\**************************/
/*! exports provided: EnvironmentHelper, PhotoDome, _forceSceneHelpersToBundle, VideoDome */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _environmentHelper__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./environmentHelper */ "./Helpers/environmentHelper.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return _environmentHelper__WEBPACK_IMPORTED_MODULE_0__["EnvironmentHelper"]; });
/* harmony import */ var _photoDome__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./photoDome */ "./Helpers/photoDome.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return _photoDome__WEBPACK_IMPORTED_MODULE_1__["PhotoDome"]; });
/* harmony import */ var _sceneHelpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sceneHelpers */ "./Helpers/sceneHelpers.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _sceneHelpers__WEBPACK_IMPORTED_MODULE_2__["_forceSceneHelpersToBundle"]; });
/* harmony import */ var _videoDome__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./videoDome */ "./Helpers/videoDome.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return _videoDome__WEBPACK_IMPORTED_MODULE_3__["VideoDome"]; });
/***/ }),
/***/ "./Helpers/photoDome.ts":
/*!******************************!*\
!*** ./Helpers/photoDome.ts ***!
\******************************/
/*! exports provided: PhotoDome */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return PhotoDome; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _textureDome__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./textureDome */ "./Helpers/textureDome.ts");
/**
* Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
* As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
* This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
* Potential additions to this helper include zoom and and non-infinite distance rendering effects.
*/
var PhotoDome = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PhotoDome, _super);
function PhotoDome() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(PhotoDome.prototype, "photoTexture", {
/**
* Gets or sets the texture being displayed on the sphere
*/
get: function () {
return this.texture;
},
/**
* sets the texture being displayed on the sphere
*/
set: function (value) {
this.texture = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PhotoDome.prototype, "imageMode", {
/**
* Gets the current video mode for the video. It can be:
* * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.
* * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.
* * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.
*/
get: function () {
return this.textureMode;
},
/**
* Sets the current video mode for the video. It can be:
* * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.
* * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.
* * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.
*/
set: function (value) {
this.textureMode = value;
},
enumerable: false,
configurable: true
});
PhotoDome.prototype._initTexture = function (urlsOrElement, scene, options) {
var _this = this;
return new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"](urlsOrElement, scene, true, !this._useDirectMapping, undefined, undefined, function (message, exception) {
_this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
if (_this.onError) {
_this.onError(message, exception);
}
});
};
/**
* Define the image as a Monoscopic panoramic 360 image.
*/
PhotoDome.MODE_MONOSCOPIC = _textureDome__WEBPACK_IMPORTED_MODULE_2__["TextureDome"].MODE_MONOSCOPIC;
/**
* Define the image as a Stereoscopic TopBottom/OverUnder panoramic 360 image.
*/
PhotoDome.MODE_TOPBOTTOM = _textureDome__WEBPACK_IMPORTED_MODULE_2__["TextureDome"].MODE_TOPBOTTOM;
/**
* Define the image as a Stereoscopic Side by Side panoramic 360 image.
*/
PhotoDome.MODE_SIDEBYSIDE = _textureDome__WEBPACK_IMPORTED_MODULE_2__["TextureDome"].MODE_SIDEBYSIDE;
return PhotoDome;
}(_textureDome__WEBPACK_IMPORTED_MODULE_2__["TextureDome"]));
/***/ }),
/***/ "./Helpers/sceneHelpers.ts":
/*!*********************************!*\
!*** ./Helpers/sceneHelpers.ts ***!
\*********************************/
/*! exports provided: _forceSceneHelpersToBundle */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _forceSceneHelpersToBundle; });
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../scene */ "./scene.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/standardMaterial */ "./Materials/standardMaterial.ts");
/* harmony import */ var _Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/PBR/pbrMaterial */ "./Materials/PBR/pbrMaterial.ts");
/* harmony import */ var _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Lights/hemisphericLight */ "./Lights/hemisphericLight.ts");
/* harmony import */ var _environmentHelper__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./environmentHelper */ "./Helpers/environmentHelper.ts");
/* harmony import */ var _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Cameras/freeCamera */ "./Cameras/freeCamera.ts");
/* harmony import */ var _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Cameras/arcRotateCamera */ "./Cameras/arcRotateCamera.ts");
/* harmony import */ var _Cameras_VR_vrExperienceHelper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Cameras/VR/vrExperienceHelper */ "./Cameras/VR/vrExperienceHelper.ts");
/* harmony import */ var _Materials_Textures_Loaders_ddsTextureLoader__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Materials/Textures/Loaders/ddsTextureLoader */ "./Materials/Textures/Loaders/ddsTextureLoader.ts");
/* harmony import */ var _Materials_Textures_Loaders_envTextureLoader__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Materials/Textures/Loaders/envTextureLoader */ "./Materials/Textures/Loaders/envTextureLoader.ts");
/* harmony import */ var _Materials_Textures_Loaders_ktxTextureLoader__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Materials/Textures/Loaders/ktxTextureLoader */ "./Materials/Textures/Loaders/ktxTextureLoader.ts");
/* harmony import */ var _Meshes_Builders_boxBuilder__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Meshes/Builders/boxBuilder */ "./Meshes/Builders/boxBuilder.ts");
/* harmony import */ var _XR_webXRDefaultExperience__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../XR/webXRDefaultExperience */ "./XR/webXRDefaultExperience.ts");
/** @hidden */
var _forceSceneHelpersToBundle = true;
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultLight = function (replace) {
if (replace === void 0) { replace = false; }
// Dispose existing light in replace mode.
if (replace) {
if (this.lights) {
for (var i = 0; i < this.lights.length; i++) {
this.lights[i].dispose();
}
}
}
// Light
if (this.lights.length === 0) {
new _Lights_hemisphericLight__WEBPACK_IMPORTED_MODULE_7__["HemisphericLight"]("default light", _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up(), this);
}
};
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
if (replace === void 0) { replace = false; }
if (attachCameraControls === void 0) { attachCameraControls = false; }
// Dispose existing camera in replace mode.
if (replace) {
if (this.activeCamera) {
this.activeCamera.dispose();
this.activeCamera = null;
}
}
// Camera
if (!this.activeCamera) {
var worldExtends = this.getWorldExtends(function (mesh) { return mesh.isVisible && mesh.isEnabled(); });
var worldSize = worldExtends.max.subtract(worldExtends.min);
var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
var camera;
var radius = worldSize.length() * 1.5;
// empty scene scenario!
if (!isFinite(radius)) {
radius = 1;
worldCenter.copyFromFloats(0, 0, 0);
}
if (createArcRotateCamera) {
var arcRotateCamera = new _Cameras_arcRotateCamera__WEBPACK_IMPORTED_MODULE_10__["ArcRotateCamera"]("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
arcRotateCamera.lowerRadiusLimit = radius * 0.01;
arcRotateCamera.wheelPrecision = 100 / radius;
camera = arcRotateCamera;
}
else {
var freeCamera = new _Cameras_freeCamera__WEBPACK_IMPORTED_MODULE_9__["FreeCamera"]("default camera", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](worldCenter.x, worldCenter.y, -radius), this);
freeCamera.setTarget(worldCenter);
camera = freeCamera;
}
camera.minZ = radius * 0.01;
camera.maxZ = radius * 1000;
camera.speed = radius * 0.2;
this.activeCamera = camera;
var canvas = this.getEngine().getInputElement();
if (attachCameraControls && canvas) {
camera.attachControl(canvas);
}
}
};
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
if (replace === void 0) { replace = false; }
if (attachCameraControls === void 0) { attachCameraControls = false; }
this.createDefaultLight(replace);
this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
};
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
if (pbr === void 0) { pbr = false; }
if (scale === void 0) { scale = 1000; }
if (blur === void 0) { blur = 0; }
if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
if (!environmentTexture) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Can not create default skybox without environment texture.");
return null;
}
if (setGlobalEnvTexture) {
if (environmentTexture) {
this.environmentTexture = environmentTexture;
}
}
// Skybox
var hdrSkybox = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_3__["Mesh"].CreateBox("hdrSkyBox", scale, this);
if (pbr) {
var hdrSkyboxMaterial = new _Materials_PBR_pbrMaterial__WEBPACK_IMPORTED_MODULE_6__["PBRMaterial"]("skyBox", this);
hdrSkyboxMaterial.backFaceCulling = false;
hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
if (hdrSkyboxMaterial.reflectionTexture) {
hdrSkyboxMaterial.reflectionTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].SKYBOX_MODE;
}
hdrSkyboxMaterial.microSurface = 1.0 - blur;
hdrSkyboxMaterial.disableLighting = true;
hdrSkyboxMaterial.twoSidedLighting = true;
hdrSkybox.infiniteDistance = true;
hdrSkybox.material = hdrSkyboxMaterial;
}
else {
var skyboxMaterial = new _Materials_standardMaterial__WEBPACK_IMPORTED_MODULE_5__["StandardMaterial"]("skyBox", this);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = environmentTexture.clone();
if (skyboxMaterial.reflectionTexture) {
skyboxMaterial.reflectionTexture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].SKYBOX_MODE;
}
skyboxMaterial.disableLighting = true;
hdrSkybox.infiniteDistance = true;
hdrSkybox.material = skyboxMaterial;
}
hdrSkybox.isPickable = false;
return hdrSkybox;
};
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultEnvironment = function (options) {
if (_environmentHelper__WEBPACK_IMPORTED_MODULE_8__["EnvironmentHelper"]) {
return new _environmentHelper__WEBPACK_IMPORTED_MODULE_8__["EnvironmentHelper"](options, this);
}
return null;
};
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultVRExperience = function (webVROptions) {
if (webVROptions === void 0) { webVROptions = {}; }
return new _Cameras_VR_vrExperienceHelper__WEBPACK_IMPORTED_MODULE_11__["VRExperienceHelper"](this, webVROptions);
};
_scene__WEBPACK_IMPORTED_MODULE_1__["Scene"].prototype.createDefaultXRExperienceAsync = function (options) {
if (options === void 0) { options = {}; }
return _XR_webXRDefaultExperience__WEBPACK_IMPORTED_MODULE_16__["WebXRDefaultExperience"].CreateAsync(this, options).then(function (helper) {
return helper;
});
};
/***/ }),
/***/ "./Helpers/textureDome.ts":
/*!********************************!*\
!*** ./Helpers/textureDome.ts ***!
\********************************/
/*! exports provided: TextureDome */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextureDome", function() { return TextureDome; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Meshes/transformNode */ "./Meshes/transformNode.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Background/backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts");
/* harmony import */ var _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/Builders/sphereBuilder */ "./Meshes/Builders/sphereBuilder.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Maths/math */ "./Maths/math.ts");
/**
* Display a 360/180 degree texture on an approximately spherical surface, useful for VR applications or skyboxes.
* As a subclass of TransformNode, this allow parenting to the camera or multiple textures with different locations in the scene.
* This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
* Potential additions to this helper include zoom and and non-infinite distance rendering effects.
*/
var TextureDome = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TextureDome, _super);
/**
* Create an instance of this class and pass through the parameters to the relevant classes- Texture, StandardMaterial, and Mesh.
* @param name Element's name, child elements will append suffixes for their own names.
* @param textureUrlOrElement defines the url(s) or the (video) HTML element to use
* @param options An object containing optional or exposed sub element properties
*/
function TextureDome(name, textureUrlOrElement, options, scene, onError) {
if (onError === void 0) { onError = null; }
var _this = _super.call(this, name, scene) || this;
_this.onError = onError;
_this._halfDome = false;
_this._useDirectMapping = false;
_this._textureMode = TextureDome.MODE_MONOSCOPIC;
/**
* Oberserver used in Stereoscopic VR Mode.
*/
_this._onBeforeCameraRenderObserver = null;
/**
* Observable raised when an error occured while loading the 360 image
*/
_this.onLoadErrorObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_6__["Observable"]();
scene = _this.getScene();
// set defaults and manage values
name = name || "textureDome";
options.resolution = Math.abs(options.resolution) | 0 || 32;
options.clickToPlay = Boolean(options.clickToPlay);
options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
options.loop = options.loop === undefined ? true : Boolean(options.loop);
options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
if (options.useDirectMapping === undefined) {
_this._useDirectMapping = true;
}
else {
_this._useDirectMapping = options.useDirectMapping;
}
if (options.faceForward === undefined) {
options.faceForward = true;
}
_this._setReady(false);
_this._mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].BACKSIDE);
// configure material
var material = (_this._material = new _Materials_Background_backgroundMaterial__WEBPACK_IMPORTED_MODULE_4__["BackgroundMaterial"](name + "_material", scene));
material.useEquirectangularFOV = true;
material.fovMultiplier = 1.0;
material.opacityFresnel = false;
var texture = _this._initTexture(textureUrlOrElement, scene, options);
_this.texture = texture;
// configure mesh
_this._mesh.material = material;
_this._mesh.parent = _this;
// create a (disabled until needed) mask to cover unneeded segments of 180 texture.
_this._halfDomeMask = _Meshes_Builders_sphereBuilder__WEBPACK_IMPORTED_MODULE_5__["SphereBuilder"].CreateSphere("", { slice: 0.5, diameter: options.size * 0.98, segments: options.resolution * 2, sideOrientation: _Meshes_mesh__WEBPACK_IMPORTED_MODULE_2__["Mesh"].BACKSIDE }, scene);
_this._halfDomeMask.rotate(_Maths_math__WEBPACK_IMPORTED_MODULE_8__["Axis"].X, -Math.PI / 2);
// set the parent, so it will always be positioned correctly AND will be disposed when the main sphere is disposed
_this._halfDomeMask.parent = _this._mesh;
_this._halfDome = !!options.halfDomeMode;
// enable or disable according to the settings
_this._halfDomeMask.setEnabled(_this._halfDome);
// create
_this._texture.anisotropicFilteringLevel = 1;
_this._texture.onLoadObservable.addOnce(function () {
_this._setReady(true);
});
// Initial rotation
if (options.faceForward && scene.activeCamera) {
var camera = scene.activeCamera;
var forward = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Forward();
var direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_7__["Vector3"].TransformNormal(forward, camera.getViewMatrix());
direction.normalize();
_this.rotation.y = Math.acos(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_7__["Vector3"].Dot(forward, direction));
}
_this._changeTextureMode(_this._textureMode);
return _this;
}
Object.defineProperty(TextureDome.prototype, "texture", {
/**
* Gets the texture being displayed on the sphere
*/
get: function () {
return this._texture;
},
/**
* Sets the texture being displayed on the sphere
*/
set: function (newTexture) {
if (this._texture === newTexture) {
return;
}
this._texture = newTexture;
if (this._useDirectMapping) {
this._texture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE;
this._texture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE;
this._material.diffuseTexture = this._texture;
}
else {
this._texture.coordinatesMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
this._texture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_3__["Texture"].CLAMP_ADDRESSMODE;
this._material.reflectionTexture = this._texture;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureDome.prototype, "mesh", {
/**
* Gets the mesh used for the dome.
*/
get: function () {
return this._mesh;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureDome.prototype, "fovMultiplier", {
/**
* The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
* Also see the options.resolution property.
*/
get: function () {
return this._material.fovMultiplier;
},
set: function (value) {
this._material.fovMultiplier = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureDome.prototype, "textureMode", {
/**
* Gets or set the current texture mode for the texture. It can be:
* * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.
* * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.
* * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.
*/
get: function () {
return this._textureMode;
},
/**
* Sets the current texture mode for the texture. It can be:
* * TextureDome.MODE_MONOSCOPIC : Define the texture source as a Monoscopic panoramic 360.
* * TextureDome.MODE_TOPBOTTOM : Define the texture source as a Stereoscopic TopBottom/OverUnder panoramic 360.
* * TextureDome.MODE_SIDEBYSIDE : Define the texture source as a Stereoscopic Side by Side panoramic 360.
*/
set: function (value) {
if (this._textureMode === value) {
return;
}
this._changeTextureMode(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureDome.prototype, "halfDome", {
/**
* Is it a 180 degrees dome (half dome) or 360 texture (full dome)
*/
get: function () {
return this._halfDome;
},
/**
* Set the halfDome mode. If set, only the front (180 degrees) will be displayed and the back will be blacked out.
*/
set: function (enabled) {
this._halfDome = enabled;
this._halfDomeMask.setEnabled(enabled);
},
enumerable: false,
configurable: true
});
TextureDome.prototype._changeTextureMode = function (value) {
var _this = this;
this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
this._textureMode = value;
// Default Setup and Reset.
this._texture.uScale = 1;
this._texture.vScale = 1;
this._texture.uOffset = 0;
this._texture.vOffset = 0;
switch (value) {
case TextureDome.MODE_MONOSCOPIC:
if (this._halfDome) {
this._texture.uScale = 2;
this._texture.uOffset = -1;
}
break;
case TextureDome.MODE_SIDEBYSIDE:
// in half-dome mode the uScale should be double of 360 texture
// Use 0.99999 to boost perf by not switching program
this._texture.uScale = this._halfDome ? 0.99999 : 0.5;
var rightOffset_1 = this._halfDome ? 0.0 : 0.5;
var leftOffset_1 = this._halfDome ? 0.5 : 0.0;
this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) {
_this._texture.uOffset = camera.isRightCamera ? rightOffset_1 : leftOffset_1;
});
break;
case TextureDome.MODE_TOPBOTTOM:
// in half-dome mode the vScale should be double of 360 texture
// Use 0.99999 to boost perf by not switching program
this._texture.vScale = this._halfDome ? 0.99999 : 0.5;
this._onBeforeCameraRenderObserver = this._scene.onBeforeCameraRenderObservable.add(function (camera) {
_this._texture.vOffset = camera.isRightCamera ? 0.5 : 0.0;
});
break;
}
};
/**
* Releases resources associated with this node.
* @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
* @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
*/
TextureDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
this._texture.dispose();
this._mesh.dispose();
this._material.dispose();
this._scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
this.onLoadErrorObservable.clear();
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
/**
* Define the source as a Monoscopic panoramic 360/180.
*/
TextureDome.MODE_MONOSCOPIC = 0;
/**
* Define the source as a Stereoscopic TopBottom/OverUnder panoramic 360/180.
*/
TextureDome.MODE_TOPBOTTOM = 1;
/**
* Define the source as a Stereoscopic Side by Side panoramic 360/180.
*/
TextureDome.MODE_SIDEBYSIDE = 2;
return TextureDome;
}(_Meshes_transformNode__WEBPACK_IMPORTED_MODULE_1__["TransformNode"]));
/***/ }),
/***/ "./Helpers/videoDome.ts":
/*!******************************!*\
!*** ./Helpers/videoDome.ts ***!
\******************************/
/*! exports provided: VideoDome */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return VideoDome; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Textures_videoTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Materials/Textures/videoTexture */ "./Materials/Textures/videoTexture.ts");
/* harmony import */ var _textureDome__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./textureDome */ "./Helpers/textureDome.ts");
/**
* Display a 360/180 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
* As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
* This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
* Potential additions to this helper include zoom and and non-infinite distance rendering effects.
*/
var VideoDome = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VideoDome, _super);
function VideoDome() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(VideoDome.prototype, "videoTexture", {
/**
* Get the video texture associated with this video dome
*/
get: function () {
return this._texture;
},
enumerable: false,
configurable: true
});
Object.defineProperty(VideoDome.prototype, "videoMode", {
/**
* Get the video mode of this dome
*/
get: function () {
return this.textureMode;
},
/**
* Set the video mode of this dome.
* @see textureMode
*/
set: function (value) {
this.textureMode = value;
},
enumerable: false,
configurable: true
});
VideoDome.prototype._initTexture = function (urlsOrElement, scene, options) {
var _this = this;
var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
var texture = new _Materials_Textures_videoTexture__WEBPACK_IMPORTED_MODULE_2__["VideoTexture"]((this.name || "videoDome") + "_texture", urlsOrElement, scene, false, this._useDirectMapping, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"].TRILINEAR_SAMPLINGMODE, tempOptions);
// optional configuration
if (options.clickToPlay) {
scene.onPointerUp = function () {
_this._texture.video.play();
};
}
return texture;
};
/**
* Define the video source as a Monoscopic panoramic 360 video.
*/
VideoDome.MODE_MONOSCOPIC = _textureDome__WEBPACK_IMPORTED_MODULE_3__["TextureDome"].MODE_MONOSCOPIC;
/**
* Define the video source as a Stereoscopic TopBottom/OverUnder panoramic 360 video.
*/
VideoDome.MODE_TOPBOTTOM = _textureDome__WEBPACK_IMPORTED_MODULE_3__["TextureDome"].MODE_TOPBOTTOM;
/**
* Define the video source as a Stereoscopic Side by Side panoramic 360 video.
*/
VideoDome.MODE_SIDEBYSIDE = _textureDome__WEBPACK_IMPORTED_MODULE_3__["TextureDome"].MODE_SIDEBYSIDE;
return VideoDome;
}(_textureDome__WEBPACK_IMPORTED_MODULE_3__["TextureDome"]));
/***/ }),
/***/ "./Inputs/scene.inputManager.ts":
/*!**************************************!*\
!*** ./Inputs/scene.inputManager.ts ***!
\**************************************/
/*! exports provided: InputManager */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputManager", function() { return InputManager; });
/* harmony import */ var _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Events/pointerEvents */ "./Events/pointerEvents.ts");
/* harmony import */ var _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Actions/abstractActionManager */ "./Actions/abstractActionManager.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Actions/actionEvent */ "./Actions/actionEvent.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Events/keyboardEvents */ "./Events/keyboardEvents.ts");
/** @hidden */
var _ClickInfo = /** @class */ (function () {
function _ClickInfo() {
this._singleClick = false;
this._doubleClick = false;
this._hasSwiped = false;
this._ignore = false;
}
Object.defineProperty(_ClickInfo.prototype, "singleClick", {
get: function () {
return this._singleClick;
},
set: function (b) {
this._singleClick = b;
},
enumerable: false,
configurable: true
});
Object.defineProperty(_ClickInfo.prototype, "doubleClick", {
get: function () {
return this._doubleClick;
},
set: function (b) {
this._doubleClick = b;
},
enumerable: false,
configurable: true
});
Object.defineProperty(_ClickInfo.prototype, "hasSwiped", {
get: function () {
return this._hasSwiped;
},
set: function (b) {
this._hasSwiped = b;
},
enumerable: false,
configurable: true
});
Object.defineProperty(_ClickInfo.prototype, "ignore", {
get: function () {
return this._ignore;
},
set: function (b) {
this._ignore = b;
},
enumerable: false,
configurable: true
});
return _ClickInfo;
}());
/**
* Class used to manage all inputs for the scene.
*/
var InputManager = /** @class */ (function () {
/**
* Creates a new InputManager
* @param scene defines the hosting scene
*/
function InputManager(scene) {
/** This is a defensive check to not allow control attachment prior to an already active one. If already attached, previous control is unattached before attaching the new one. */
this._alreadyAttached = false;
// Pointers
this._wheelEventName = "";
this._meshPickProceed = false;
this._currentPickResult = null;
this._previousPickResult = null;
this._totalPointersPressed = 0;
this._doubleClickOccured = false;
this._pointerX = 0;
this._pointerY = 0;
this._startingPointerPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0);
this._previousStartingPointerPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 0);
this._startingPointerTime = 0;
this._previousStartingPointerTime = 0;
this._pointerCaptures = {};
this._meshUnderPointerId = [];
this._scene = scene;
}
Object.defineProperty(InputManager.prototype, "meshUnderPointer", {
/**
* Gets the mesh that is currently under the pointer
*/
get: function () {
return this._pointerOverMesh;
},
enumerable: false,
configurable: true
});
/**
* When using more than one pointer (for example in XR) you can get the mesh under the specific pointer
* @param pointerId the pointer id to use
* @returns The mesh under this pointer id or null if not found
*/
InputManager.prototype.getMeshUnderPointerByPointerId = function (pointerId) {
return this._meshUnderPointerId[pointerId];
};
Object.defineProperty(InputManager.prototype, "unTranslatedPointer", {
/**
* Gets the pointer coordinates in 2D without any translation (ie. straight out of the pointer event)
*/
get: function () {
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](this._unTranslatedPointerX, this._unTranslatedPointerY);
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputManager.prototype, "pointerX", {
/**
* Gets or sets the current on-screen X position of the pointer
*/
get: function () {
return this._pointerX;
},
set: function (value) {
this._pointerX = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputManager.prototype, "pointerY", {
/**
* Gets or sets the current on-screen Y position of the pointer
*/
get: function () {
return this._pointerY;
},
set: function (value) {
this._pointerY = value;
},
enumerable: false,
configurable: true
});
InputManager.prototype._updatePointerPosition = function (evt) {
var canvasRect = this._scene.getEngine().getInputElementClientRect();
if (!canvasRect) {
return;
}
this._pointerX = evt.clientX - canvasRect.left;
this._pointerY = evt.clientY - canvasRect.top;
this._unTranslatedPointerX = this._pointerX;
this._unTranslatedPointerY = this._pointerY;
};
InputManager.prototype._processPointerMove = function (pickResult, evt) {
var scene = this._scene;
var engine = scene.getEngine();
var canvas = engine.getInputElement();
if (!canvas) {
return;
}
canvas.tabIndex = engine.canvasTabIndex;
// Restore pointer
if (!scene.doNotHandleCursors) {
canvas.style.cursor = scene.defaultCursor;
}
var isMeshPicked = pickResult && pickResult.hit && pickResult.pickedMesh ? true : false;
if (isMeshPicked) {
scene.setPointerOverMesh(pickResult.pickedMesh, evt.pointerId);
if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
if (!scene.doNotHandleCursors) {
if (this._pointerOverMesh.actionManager.hoverCursor) {
canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
}
else {
canvas.style.cursor = scene.hoverCursor;
}
}
}
}
else {
scene.setPointerOverMesh(null, evt.pointerId);
}
for (var _i = 0, _a = scene._pointerMoveStage; _i < _a.length; _i++) {
var step = _a[_i];
pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
}
if (pickResult) {
var type = evt.type === this._wheelEventName ? _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERWHEEL : _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE;
if (scene.onPointerMove) {
scene.onPointerMove(evt, pickResult, type);
}
if (scene.onPointerObservable.hasObservers()) {
var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult);
this._setRayOnPointerInfo(pi);
scene.onPointerObservable.notifyObservers(pi, type);
}
}
};
// Pointers handling
InputManager.prototype._setRayOnPointerInfo = function (pointerInfo) {
var scene = this._scene;
if (pointerInfo.pickInfo && !pointerInfo.pickInfo._pickingUnavailable) {
if (!pointerInfo.pickInfo.ray) {
pointerInfo.pickInfo.ray = scene.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity(), scene.activeCamera);
}
}
};
InputManager.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
var scene = this._scene;
var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfoPre"](type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
if (pickResult) {
pi.ray = pickResult.ray;
}
scene.onPrePointerObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return true;
}
else {
return false;
}
};
/**
* Use this method to simulate a pointer move on a mesh
* The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
* @param pickResult pickingInfo of the object wished to simulate pointer event on
* @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
*/
InputManager.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
var evt = new PointerEvent("pointermove", pointerEventInit);
if (this._checkPrePointerObservable(pickResult, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE)) {
return;
}
this._processPointerMove(pickResult, evt);
};
/**
* Use this method to simulate a pointer down on a mesh
* The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
* @param pickResult pickingInfo of the object wished to simulate pointer event on
* @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
*/
InputManager.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
var evt = new PointerEvent("pointerdown", pointerEventInit);
if (this._checkPrePointerObservable(pickResult, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN)) {
return;
}
this._processPointerDown(pickResult, evt);
};
InputManager.prototype._processPointerDown = function (pickResult, evt) {
var _this = this;
var scene = this._scene;
if (pickResult && pickResult.hit && pickResult.pickedMesh) {
this._pickedDownMesh = pickResult.pickedMesh;
var actionManager = pickResult.pickedMesh._getActionManagerForTrigger();
if (actionManager) {
if (actionManager.hasPickTriggers) {
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickDownTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
switch (evt.button) {
case 0:
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLeftPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
break;
case 1:
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnCenterPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
break;
case 2:
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnRightPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
break;
}
}
if (actionManager.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLongPressTrigger)) {
window.setTimeout(function () {
var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, function (mesh) { return (mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLongPressTrigger) && mesh == _this._pickedDownMesh); }, false, scene.cameraToUseForPointers);
if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
if (_this._totalPointersPressed !== 0 && Date.now() - _this._startingPointerTime > InputManager.LongPressDelay && !_this._isPointerSwiping()) {
_this._startingPointerTime = 0;
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnLongPressTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
}
}
}, InputManager.LongPressDelay);
}
}
}
else {
for (var _i = 0, _a = scene._pointerDownStage; _i < _a.length; _i++) {
var step = _a[_i];
pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
}
}
if (pickResult) {
var type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN;
if (scene.onPointerDown) {
scene.onPointerDown(evt, pickResult, type);
}
if (scene.onPointerObservable.hasObservers()) {
var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult);
this._setRayOnPointerInfo(pi);
scene.onPointerObservable.notifyObservers(pi, type);
}
}
};
/** @hidden */
InputManager.prototype._isPointerSwiping = function () {
return Math.abs(this._startingPointerPosition.x - this._pointerX) > InputManager.DragMovementThreshold || Math.abs(this._startingPointerPosition.y - this._pointerY) > InputManager.DragMovementThreshold;
};
/**
* Use this method to simulate a pointer up on a mesh
* The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
* @param pickResult pickingInfo of the object wished to simulate pointer event on
* @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
* @param doubleTap indicates that the pointer up event should be considered as part of a double click (false by default)
*/
InputManager.prototype.simulatePointerUp = function (pickResult, pointerEventInit, doubleTap) {
var evt = new PointerEvent("pointerup", pointerEventInit);
var clickInfo = new _ClickInfo();
if (doubleTap) {
clickInfo.doubleClick = true;
}
else {
clickInfo.singleClick = true;
}
if (this._checkPrePointerObservable(pickResult, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP)) {
return;
}
this._processPointerUp(pickResult, evt, clickInfo);
};
InputManager.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
var scene = this._scene;
if (pickResult && pickResult && pickResult.pickedMesh) {
this._pickedUpMesh = pickResult.pickedMesh;
if (this._pickedDownMesh === this._pickedUpMesh) {
if (scene.onPointerPick) {
scene.onPointerPick(evt, pickResult);
}
if (clickInfo.singleClick && !clickInfo.ignore && scene.onPointerObservable.hasObservers()) {
var type_1 = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERPICK;
var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type_1, evt, pickResult);
this._setRayOnPointerInfo(pi);
scene.onPointerObservable.notifyObservers(pi, type_1);
}
}
var actionManager = pickResult.pickedMesh._getActionManagerForTrigger();
if (actionManager && !clickInfo.ignore) {
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickUpTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
if (!clickInfo.hasSwiped && clickInfo.singleClick) {
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
}
var doubleClickActionManager = pickResult.pickedMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger);
if (clickInfo.doubleClick && doubleClickActionManager) {
doubleClickActionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(pickResult.pickedMesh, evt));
}
}
}
else {
if (!clickInfo.ignore) {
for (var _i = 0, _a = scene._pointerUpStage; _i < _a.length; _i++) {
var step = _a[_i];
pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
}
}
}
if (this._pickedDownMesh && this._pickedDownMesh !== this._pickedUpMesh) {
var pickedDownActionManager = this._pickedDownMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickOutTrigger);
if (pickedDownActionManager) {
pickedDownActionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPickOutTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(this._pickedDownMesh, evt));
}
}
var type = 0;
if (scene.onPointerObservable.hasObservers()) {
if (!clickInfo.ignore && !clickInfo.hasSwiped) {
if (clickInfo.singleClick && scene.onPointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP)) {
type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP;
}
else if (clickInfo.doubleClick && scene.onPointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP)) {
type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP;
}
if (type) {
var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult);
this._setRayOnPointerInfo(pi);
scene.onPointerObservable.notifyObservers(pi, type);
}
}
if (!clickInfo.ignore) {
type = _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP;
var pi = new _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"](type, evt, pickResult);
this._setRayOnPointerInfo(pi);
scene.onPointerObservable.notifyObservers(pi, type);
}
}
if (scene.onPointerUp && !clickInfo.ignore) {
scene.onPointerUp(evt, pickResult, type);
}
};
/**
* Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
* @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
* @returns true if the pointer was captured
*/
InputManager.prototype.isPointerCaptured = function (pointerId) {
if (pointerId === void 0) { pointerId = 0; }
return this._pointerCaptures[pointerId];
};
/**
* Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
* @param attachUp defines if you want to attach events to pointerup
* @param attachDown defines if you want to attach events to pointerdown
* @param attachMove defines if you want to attach events to pointermove
* @param elementToAttachTo defines the target DOM element to attach to (will use the canvas by default)
*/
InputManager.prototype.attachControl = function (attachUp, attachDown, attachMove, elementToAttachTo) {
var _this = this;
if (attachUp === void 0) { attachUp = true; }
if (attachDown === void 0) { attachDown = true; }
if (attachMove === void 0) { attachMove = true; }
if (elementToAttachTo === void 0) { elementToAttachTo = null; }
var scene = this._scene;
if (!elementToAttachTo) {
elementToAttachTo = scene.getEngine().getInputElement();
}
if (!elementToAttachTo) {
return;
}
if (this._alreadyAttached) {
this.detachControl();
}
var engine = scene.getEngine();
this._initActionManager = function (act, clickInfo) {
if (!_this._meshPickProceed) {
var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, scene.pointerDownPredicate, false, scene.cameraToUseForPointers);
_this._currentPickResult = pickResult;
if (pickResult) {
act = pickResult.hit && pickResult.pickedMesh ? pickResult.pickedMesh._getActionManagerForTrigger() : null;
}
_this._meshPickProceed = true;
}
return act;
};
this._delayedSimpleClick = function (btn, clickInfo, cb) {
// double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
if ((Date.now() - _this._previousStartingPointerTime > InputManager.DoubleClickDelay && !_this._doubleClickOccured) || btn !== _this._previousButtonPressed) {
_this._doubleClickOccured = false;
clickInfo.singleClick = true;
clickInfo.ignore = false;
cb(clickInfo, _this._currentPickResult);
}
};
this._initClickEvent = function (obs1, obs2, evt, cb) {
var clickInfo = new _ClickInfo();
_this._currentPickResult = null;
var act = null;
var checkPicking = obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERPICK) ||
obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERPICK) ||
obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP) ||
obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP) ||
obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP) ||
obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP);
if (!checkPicking && _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"]) {
act = _this._initActionManager(act, clickInfo);
if (act) {
checkPicking = act.hasPickTriggers;
}
}
var needToIgnoreNext = false;
if (checkPicking) {
var btn = evt.button;
clickInfo.hasSwiped = _this._isPointerSwiping();
if (!clickInfo.hasSwiped) {
var checkSingleClickImmediately = !InputManager.ExclusiveDoubleClickMode;
if (!checkSingleClickImmediately) {
checkSingleClickImmediately = !obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP) && !obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP);
if (checkSingleClickImmediately && !_Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"].HasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger)) {
act = _this._initActionManager(act, clickInfo);
if (act) {
checkSingleClickImmediately = !act.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger);
}
}
}
if (checkSingleClickImmediately) {
// single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
if (Date.now() - _this._previousStartingPointerTime > InputManager.DoubleClickDelay || btn !== _this._previousButtonPressed) {
clickInfo.singleClick = true;
cb(clickInfo, _this._currentPickResult);
needToIgnoreNext = true;
}
}
// at least one double click is required to be check and exclusive double click is enabled
else {
// wait that no double click has been raised during the double click delay
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
_this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), InputManager.DoubleClickDelay);
}
var checkDoubleClick = obs1.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP) || obs2.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP);
if (!checkDoubleClick && _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"].HasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger)) {
act = _this._initActionManager(act, clickInfo);
if (act) {
checkDoubleClick = act.hasSpecificTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnDoublePickTrigger);
}
}
if (checkDoubleClick) {
// two successive keys pressed are equal, double click delay is not over and double click has not just occurred
if (btn === _this._previousButtonPressed && Date.now() - _this._previousStartingPointerTime < InputManager.DoubleClickDelay && !_this._doubleClickOccured) {
// pointer has not moved for 2 clicks, it's a double click
if (!clickInfo.hasSwiped && !_this._isPointerSwiping()) {
_this._previousStartingPointerTime = 0;
_this._doubleClickOccured = true;
clickInfo.doubleClick = true;
clickInfo.ignore = false;
if (InputManager.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
clearTimeout(_this._previousDelayedSimpleClickTimeout);
}
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
cb(clickInfo, _this._currentPickResult);
}
// if the two successive clicks are too far, it's just two simple clicks
else {
_this._doubleClickOccured = false;
_this._previousStartingPointerTime = _this._startingPointerTime;
_this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
_this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
_this._previousButtonPressed = btn;
if (InputManager.ExclusiveDoubleClickMode) {
if (_this._previousDelayedSimpleClickTimeout) {
clearTimeout(_this._previousDelayedSimpleClickTimeout);
}
_this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
cb(clickInfo, _this._previousPickResult);
}
else {
cb(clickInfo, _this._currentPickResult);
}
}
needToIgnoreNext = true;
}
// just the first click of the double has been raised
else {
_this._doubleClickOccured = false;
_this._previousStartingPointerTime = _this._startingPointerTime;
_this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
_this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
_this._previousButtonPressed = btn;
}
}
}
}
if (!needToIgnoreNext) {
cb(clickInfo, _this._currentPickResult);
}
};
this._onPointerMove = function (evt) {
// preserve compatibility with Safari when pointerId is not present
if (evt.pointerId === undefined) {
evt.pointerId = 0;
}
_this._updatePointerPosition(evt);
// PreObservable support
if (_this._checkPrePointerObservable(null, evt, evt.type === _this._wheelEventName ? _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERWHEEL : _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERMOVE)) {
return;
}
if (!scene.cameraToUseForPointers && !scene.activeCamera) {
return;
}
if (!scene.pointerMovePredicate) {
scene.pointerMovePredicate = function (mesh) {
return mesh.isPickable &&
mesh.isVisible &&
mesh.isReady() &&
mesh.isEnabled() &&
(mesh.enablePointerMoveEvents || scene.constantlyUpdateMeshUnderPointer || mesh._getActionManagerForTrigger() != null) &&
(!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);
};
}
// Meshes
var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, scene.pointerMovePredicate, false, scene.cameraToUseForPointers);
_this._processPointerMove(pickResult, evt);
};
this._onPointerDown = function (evt) {
_this._totalPointersPressed++;
_this._pickedDownMesh = null;
_this._meshPickProceed = false;
// preserve compatibility with Safari when pointerId is not present
if (evt.pointerId === undefined) {
evt.pointerId = 0;
}
_this._updatePointerPosition(evt);
if (scene.preventDefaultOnPointerDown && elementToAttachTo) {
evt.preventDefault();
elementToAttachTo.focus();
}
_this._startingPointerPosition.x = _this._pointerX;
_this._startingPointerPosition.y = _this._pointerY;
_this._startingPointerTime = Date.now();
// PreObservable support
if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOWN)) {
return;
}
if (!scene.cameraToUseForPointers && !scene.activeCamera) {
return;
}
_this._pointerCaptures[evt.pointerId] = true;
if (!scene.pointerDownPredicate) {
scene.pointerDownPredicate = function (mesh) {
return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);
};
}
// Meshes
_this._pickedDownMesh = null;
var pickResult = scene.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, scene.pointerDownPredicate, false, scene.cameraToUseForPointers);
_this._processPointerDown(pickResult, evt);
};
this._onPointerUp = function (evt) {
if (_this._totalPointersPressed === 0) {
// We are attaching the pointer up to windows because of a bug in FF
return; // So we need to test it the pointer down was pressed before.
}
_this._totalPointersPressed--;
_this._pickedUpMesh = null;
_this._meshPickProceed = false;
// preserve compatibility with Safari when pointerId is not present
if (evt.pointerId === undefined) {
evt.pointerId = 0;
}
_this._updatePointerPosition(evt);
if (scene.preventDefaultOnPointerUp && elementToAttachTo) {
evt.preventDefault();
elementToAttachTo.focus();
}
_this._initClickEvent(scene.onPrePointerObservable, scene.onPointerObservable, evt, function (clickInfo, pickResult) {
// PreObservable support
if (scene.onPrePointerObservable.hasObservers()) {
if (!clickInfo.ignore) {
if (!clickInfo.hasSwiped) {
if (clickInfo.singleClick && scene.onPrePointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP)) {
if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERTAP)) {
return;
}
}
if (clickInfo.doubleClick && scene.onPrePointerObservable.hasSpecificMask(_Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP)) {
if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERDOUBLETAP)) {
return;
}
}
}
if (_this._checkPrePointerObservable(null, evt, _Events_pointerEvents__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"].POINTERUP)) {
return;
}
}
}
if (!_this._pointerCaptures[evt.pointerId]) {
return;
}
_this._pointerCaptures[evt.pointerId] = false;
if (!scene.cameraToUseForPointers && !scene.activeCamera) {
return;
}
if (!scene.pointerUpPredicate) {
scene.pointerUpPredicate = function (mesh) {
return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (!scene.cameraToUseForPointers || (scene.cameraToUseForPointers.layerMask & mesh.layerMask) !== 0);
};
}
// Meshes
if (!_this._meshPickProceed && ((_Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"] && _Actions_abstractActionManager__WEBPACK_IMPORTED_MODULE_1__["AbstractActionManager"].HasTriggers) || scene.onPointerObservable.hasObservers())) {
_this._initActionManager(null, clickInfo);
}
if (!pickResult) {
pickResult = _this._currentPickResult;
}
_this._processPointerUp(pickResult, evt, clickInfo);
_this._previousPickResult = _this._currentPickResult;
});
};
this._onKeyDown = function (evt) {
var type = _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardEventTypes"].KEYDOWN;
if (scene.onPreKeyboardObservable.hasObservers()) {
var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfoPre"](type, evt);
scene.onPreKeyboardObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (scene.onKeyboardObservable.hasObservers()) {
var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfo"](type, evt);
scene.onKeyboardObservable.notifyObservers(pi, type);
}
if (scene.actionManager) {
scene.actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnKeyDownTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNewFromScene(scene, evt));
}
};
this._onKeyUp = function (evt) {
var type = _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardEventTypes"].KEYUP;
if (scene.onPreKeyboardObservable.hasObservers()) {
var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfoPre"](type, evt);
scene.onPreKeyboardObservable.notifyObservers(pi, type);
if (pi.skipOnPointerObservable) {
return;
}
}
if (scene.onKeyboardObservable.hasObservers()) {
var pi = new _Events_keyboardEvents__WEBPACK_IMPORTED_MODULE_6__["KeyboardInfo"](type, evt);
scene.onKeyboardObservable.notifyObservers(pi, type);
}
if (scene.actionManager) {
scene.actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnKeyUpTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNewFromScene(scene, evt));
}
};
// Keyboard events
this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add((function () {
var fn = function () {
if (!elementToAttachTo) {
return;
}
elementToAttachTo.addEventListener("keydown", _this._onKeyDown, false);
elementToAttachTo.addEventListener("keyup", _this._onKeyUp, false);
};
if (document.activeElement === elementToAttachTo) {
fn();
}
return fn;
})());
this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
if (!elementToAttachTo) {
return;
}
elementToAttachTo.removeEventListener("keydown", _this._onKeyDown);
elementToAttachTo.removeEventListener("keyup", _this._onKeyUp);
});
// Pointer events
var eventPrefix = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetPointerPrefix(engine);
if (attachMove) {
elementToAttachTo.addEventListener(eventPrefix + "move", this._onPointerMove, false);
// Wheel
this._wheelEventName =
"onwheel" in document.createElement("div")
? "wheel" // Modern browsers support "wheel"
: document.onmousewheel !== undefined
? "mousewheel" // Webkit and IE support at least "mousewheel"
: "DOMMouseScroll"; // let's assume that remaining browsers are older Firefox
elementToAttachTo.addEventListener(this._wheelEventName, this._onPointerMove, false);
}
if (attachDown) {
elementToAttachTo.addEventListener(eventPrefix + "down", this._onPointerDown, false);
}
if (attachUp) {
var hostWindow = scene.getEngine().getHostWindow();
if (hostWindow) {
hostWindow.addEventListener(eventPrefix + "up", this._onPointerUp, false);
}
}
this._alreadyAttached = true;
};
/**
* Detaches all event handlers
*/
InputManager.prototype.detachControl = function () {
var canvas = this._scene.getEngine().getInputElement();
var engine = this._scene.getEngine();
var eventPrefix = _Misc_tools__WEBPACK_IMPORTED_MODULE_5__["Tools"].GetPointerPrefix(engine);
if (!canvas) {
return;
}
if (!this._alreadyAttached) {
return;
}
// Pointer
canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
canvas.removeEventListener(this._wheelEventName, this._onPointerMove);
canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
window.removeEventListener(eventPrefix + "up", this._onPointerUp);
// Blur / Focus
if (this._onCanvasBlurObserver) {
engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
}
if (this._onCanvasFocusObserver) {
engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
}
// Keyboard
canvas.removeEventListener("keydown", this._onKeyDown);
canvas.removeEventListener("keyup", this._onKeyUp);
// Cursor
if (!this._scene.doNotHandleCursors) {
canvas.style.cursor = this._scene.defaultCursor;
}
this._alreadyAttached = false;
};
/**
* Force the value of meshUnderPointer
* @param mesh defines the mesh to use
* @param pointerId optional pointer id when using more than one pointer. Defaults to 0
*/
InputManager.prototype.setPointerOverMesh = function (mesh, pointerId) {
if (pointerId === void 0) { pointerId = 0; }
// Sanity check
if (pointerId < 0) {
pointerId = 0;
}
if (this._meshUnderPointerId[pointerId] === mesh) {
return;
}
var underPointerMesh = this._meshUnderPointerId[pointerId];
var actionManager;
if (underPointerMesh) {
actionManager = underPointerMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOutTrigger);
if (actionManager) {
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOutTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(underPointerMesh, undefined, { pointerId: pointerId }));
}
}
this._meshUnderPointerId[pointerId] = mesh;
this._pointerOverMesh = mesh;
underPointerMesh = this._meshUnderPointerId[pointerId];
if (underPointerMesh) {
actionManager = underPointerMesh._getActionManagerForTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOverTrigger);
if (actionManager) {
actionManager.processTrigger(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].ACTION_OnPointerOverTrigger, _Actions_actionEvent__WEBPACK_IMPORTED_MODULE_4__["ActionEvent"].CreateNew(underPointerMesh, undefined, { pointerId: pointerId }));
}
}
};
/**
* Gets the mesh under the pointer
* @returns a Mesh or null if no mesh is under the pointer
*/
InputManager.prototype.getPointerOverMesh = function () {
return this._pointerOverMesh;
};
/** The distance in pixel that you have to move to prevent some events */
InputManager.DragMovementThreshold = 10; // in pixels
/** Time in milliseconds to wait to raise long press events if button is still pressed */
InputManager.LongPressDelay = 500; // in milliseconds
/** Time in milliseconds with two consecutive clicks will be considered as a double click */
InputManager.DoubleClickDelay = 300; // in milliseconds
/** If you need to check double click without raising a single click at first click, enable this flag */
InputManager.ExclusiveDoubleClickMode = false;
return InputManager;
}());
/***/ }),
/***/ "./Instrumentation/engineInstrumentation.ts":
/*!**************************************************!*\
!*** ./Instrumentation/engineInstrumentation.ts ***!
\**************************************************/
/*! exports provided: EngineInstrumentation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return EngineInstrumentation; });
/* harmony import */ var _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/perfCounter */ "./Misc/perfCounter.ts");
/**
* This class can be used to get instrumentation data from a Babylon engine
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
*/
var EngineInstrumentation = /** @class */ (function () {
/**
* Instantiates a new engine instrumentation.
* This class can be used to get instrumentation data from a Babylon engine
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
* @param engine Defines the engine to instrument
*/
function EngineInstrumentation(
/**
* Define the instrumented engine.
*/
engine) {
this.engine = engine;
this._captureGPUFrameTime = false;
this._gpuFrameTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]();
this._captureShaderCompilationTime = false;
this._shaderCompilationTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]();
// Observers
this._onBeginFrameObserver = null;
this._onEndFrameObserver = null;
this._onBeforeShaderCompilationObserver = null;
this._onAfterShaderCompilationObserver = null;
}
Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
// Properties
/**
* Gets the perf counter used for GPU frame time
*/
get: function () {
return this._gpuFrameTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
/**
* Gets the GPU frame time capture status
*/
get: function () {
return this._captureGPUFrameTime;
},
/**
* Enable or disable the GPU frame time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureGPUFrameTime) {
return;
}
this._captureGPUFrameTime = value;
if (value) {
this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
if (!_this._gpuFrameTimeToken) {
_this._gpuFrameTimeToken = _this.engine.startTimeQuery();
}
});
this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
if (!_this._gpuFrameTimeToken) {
return;
}
var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
if (time > -1) {
_this._gpuFrameTimeToken = null;
_this._gpuFrameTime.fetchNewFrame();
_this._gpuFrameTime.addCount(time, true);
}
});
}
else {
this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
this._onBeginFrameObserver = null;
this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
this._onEndFrameObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
/**
* Gets the perf counter used for shader compilation time
*/
get: function () {
return this._shaderCompilationTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
/**
* Gets the shader compilation time capture status
*/
get: function () {
return this._captureShaderCompilationTime;
},
/**
* Enable or disable the shader compilation time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureShaderCompilationTime) {
return;
}
this._captureShaderCompilationTime = value;
if (value) {
this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
_this._shaderCompilationTime.fetchNewFrame();
_this._shaderCompilationTime.beginMonitoring();
});
this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
_this._shaderCompilationTime.endMonitoring();
});
}
else {
this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
this._onBeforeShaderCompilationObserver = null;
this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
this._onAfterShaderCompilationObserver = null;
}
},
enumerable: false,
configurable: true
});
/**
* Dispose and release associated resources.
*/
EngineInstrumentation.prototype.dispose = function () {
this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
this._onBeginFrameObserver = null;
this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
this._onEndFrameObserver = null;
this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
this._onBeforeShaderCompilationObserver = null;
this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
this._onAfterShaderCompilationObserver = null;
this.engine = null;
};
return EngineInstrumentation;
}());
/***/ }),
/***/ "./Instrumentation/index.ts":
/*!**********************************!*\
!*** ./Instrumentation/index.ts ***!
\**********************************/
/*! exports provided: EngineInstrumentation, SceneInstrumentation, _TimeToken */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _engineInstrumentation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./engineInstrumentation */ "./Instrumentation/engineInstrumentation.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return _engineInstrumentation__WEBPACK_IMPORTED_MODULE_0__["EngineInstrumentation"]; });
/* harmony import */ var _sceneInstrumentation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./sceneInstrumentation */ "./Instrumentation/sceneInstrumentation.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return _sceneInstrumentation__WEBPACK_IMPORTED_MODULE_1__["SceneInstrumentation"]; });
/* harmony import */ var _timeToken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./timeToken */ "./Instrumentation/timeToken.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _timeToken__WEBPACK_IMPORTED_MODULE_2__["_TimeToken"]; });
/***/ }),
/***/ "./Instrumentation/sceneInstrumentation.ts":
/*!*************************************************!*\
!*** ./Instrumentation/sceneInstrumentation.ts ***!
\*************************************************/
/*! exports provided: SceneInstrumentation */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return SceneInstrumentation; });
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/perfCounter */ "./Misc/perfCounter.ts");
/**
* This class can be used to get instrumentation data from a Babylon engine
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
*/
var SceneInstrumentation = /** @class */ (function () {
/**
* Instantiates a new scene instrumentation.
* This class can be used to get instrumentation data from a Babylon engine
* @see https://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
* @param scene Defines the scene to instrument
*/
function SceneInstrumentation(
/**
* Defines the scene to instrument
*/
scene) {
var _this = this;
this.scene = scene;
this._captureActiveMeshesEvaluationTime = false;
this._activeMeshesEvaluationTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureRenderTargetsRenderTime = false;
this._renderTargetsRenderTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureFrameTime = false;
this._frameTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureRenderTime = false;
this._renderTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureInterFrameTime = false;
this._interFrameTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureParticlesRenderTime = false;
this._particlesRenderTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureSpritesRenderTime = false;
this._spritesRenderTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._capturePhysicsTime = false;
this._physicsTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureAnimationsTime = false;
this._animationsTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
this._captureCameraRenderTime = false;
this._cameraRenderTime = new _Misc_perfCounter__WEBPACK_IMPORTED_MODULE_1__["PerfCounter"]();
// Observers
this._onBeforeActiveMeshesEvaluationObserver = null;
this._onAfterActiveMeshesEvaluationObserver = null;
this._onBeforeRenderTargetsRenderObserver = null;
this._onAfterRenderTargetsRenderObserver = null;
this._onAfterRenderObserver = null;
this._onBeforeDrawPhaseObserver = null;
this._onAfterDrawPhaseObserver = null;
this._onBeforeAnimationsObserver = null;
this._onBeforeParticlesRenderingObserver = null;
this._onAfterParticlesRenderingObserver = null;
this._onBeforeSpritesRenderingObserver = null;
this._onAfterSpritesRenderingObserver = null;
this._onBeforePhysicsObserver = null;
this._onAfterPhysicsObserver = null;
this._onAfterAnimationsObserver = null;
this._onBeforeCameraRenderObserver = null;
this._onAfterCameraRenderObserver = null;
// Before render
this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
if (_this._captureActiveMeshesEvaluationTime) {
_this._activeMeshesEvaluationTime.fetchNewFrame();
}
if (_this._captureRenderTargetsRenderTime) {
_this._renderTargetsRenderTime.fetchNewFrame();
}
if (_this._captureFrameTime) {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Scene rendering");
_this._frameTime.beginMonitoring();
}
if (_this._captureInterFrameTime) {
_this._interFrameTime.endMonitoring();
}
if (_this._captureParticlesRenderTime) {
_this._particlesRenderTime.fetchNewFrame();
}
if (_this._captureSpritesRenderTime) {
_this._spritesRenderTime.fetchNewFrame();
}
if (_this._captureAnimationsTime) {
_this._animationsTime.beginMonitoring();
}
_this.scene.getEngine()._drawCalls.fetchNewFrame();
});
// After render
this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
if (_this._captureFrameTime) {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Scene rendering");
_this._frameTime.endMonitoring();
}
if (_this._captureRenderTime) {
_this._renderTime.endMonitoring(false);
}
if (_this._captureInterFrameTime) {
_this._interFrameTime.beginMonitoring();
}
});
}
Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
// Properties
/**
* Gets the perf counter used for active meshes evaluation time
*/
get: function () {
return this._activeMeshesEvaluationTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
/**
* Gets the active meshes evaluation time capture status
*/
get: function () {
return this._captureActiveMeshesEvaluationTime;
},
/**
* Enable or disable the active meshes evaluation time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureActiveMeshesEvaluationTime) {
return;
}
this._captureActiveMeshesEvaluationTime = value;
if (value) {
this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Active meshes evaluation");
_this._activeMeshesEvaluationTime.beginMonitoring();
});
this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Active meshes evaluation");
_this._activeMeshesEvaluationTime.endMonitoring();
});
}
else {
this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
this._onBeforeActiveMeshesEvaluationObserver = null;
this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
this._onAfterActiveMeshesEvaluationObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
/**
* Gets the perf counter used for render targets render time
*/
get: function () {
return this._renderTargetsRenderTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
/**
* Gets the render targets render time capture status
*/
get: function () {
return this._captureRenderTargetsRenderTime;
},
/**
* Enable or disable the render targets render time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureRenderTargetsRenderTime) {
return;
}
this._captureRenderTargetsRenderTime = value;
if (value) {
this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Render targets rendering");
_this._renderTargetsRenderTime.beginMonitoring();
});
this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Render targets rendering");
_this._renderTargetsRenderTime.endMonitoring(false);
});
}
else {
this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
this._onBeforeRenderTargetsRenderObserver = null;
this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
this._onAfterRenderTargetsRenderObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
/**
* Gets the perf counter used for particles render time
*/
get: function () {
return this._particlesRenderTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
/**
* Gets the particles render time capture status
*/
get: function () {
return this._captureParticlesRenderTime;
},
/**
* Enable or disable the particles render time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureParticlesRenderTime) {
return;
}
this._captureParticlesRenderTime = value;
if (value) {
this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Particles");
_this._particlesRenderTime.beginMonitoring();
});
this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Particles");
_this._particlesRenderTime.endMonitoring(false);
});
}
else {
this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
this._onBeforeParticlesRenderingObserver = null;
this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
this._onAfterParticlesRenderingObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
/**
* Gets the perf counter used for sprites render time
*/
get: function () {
return this._spritesRenderTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
/**
* Gets the sprites render time capture status
*/
get: function () {
return this._captureSpritesRenderTime;
},
/**
* Enable or disable the sprites render time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureSpritesRenderTime) {
return;
}
this._captureSpritesRenderTime = value;
if (!this.scene.spriteManagers) {
return;
}
if (value) {
this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Sprites");
_this._spritesRenderTime.beginMonitoring();
});
this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Sprites");
_this._spritesRenderTime.endMonitoring(false);
});
}
else {
this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
this._onBeforeSpritesRenderingObserver = null;
this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
this._onAfterSpritesRenderingObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
/**
* Gets the perf counter used for physics time
*/
get: function () {
return this._physicsTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
/**
* Gets the physics time capture status
*/
get: function () {
return this._capturePhysicsTime;
},
/**
* Enable or disable the physics time capture
*/
set: function (value) {
var _this = this;
if (value === this._capturePhysicsTime) {
return;
}
if (!this.scene.onBeforePhysicsObservable) {
return;
}
this._capturePhysicsTime = value;
if (value) {
this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Physics");
_this._physicsTime.beginMonitoring();
});
this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Physics");
_this._physicsTime.endMonitoring();
});
}
else {
this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
this._onBeforePhysicsObserver = null;
this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
this._onAfterPhysicsObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
/**
* Gets the perf counter used for animations time
*/
get: function () {
return this._animationsTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
/**
* Gets the animations time capture status
*/
get: function () {
return this._captureAnimationsTime;
},
/**
* Enable or disable the animations time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureAnimationsTime) {
return;
}
this._captureAnimationsTime = value;
if (value) {
this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
_this._animationsTime.endMonitoring();
});
}
else {
this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
this._onAfterAnimationsObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
/**
* Gets the perf counter used for frame time capture
*/
get: function () {
return this._frameTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
/**
* Gets the frame time capture status
*/
get: function () {
return this._captureFrameTime;
},
/**
* Enable or disable the frame time capture
*/
set: function (value) {
this._captureFrameTime = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
/**
* Gets the perf counter used for inter-frames time capture
*/
get: function () {
return this._interFrameTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
/**
* Gets the inter-frames time capture status
*/
get: function () {
return this._captureInterFrameTime;
},
/**
* Enable or disable the inter-frames time capture
*/
set: function (value) {
this._captureInterFrameTime = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
/**
* Gets the perf counter used for render time capture
*/
get: function () {
return this._renderTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
/**
* Gets the render time capture status
*/
get: function () {
return this._captureRenderTime;
},
/**
* Enable or disable the render time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureRenderTime) {
return;
}
this._captureRenderTime = value;
if (value) {
this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
_this._renderTime.beginMonitoring();
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Main render");
});
this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
_this._renderTime.endMonitoring(false);
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Main render");
});
}
else {
this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
this._onBeforeDrawPhaseObserver = null;
this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
this._onAfterDrawPhaseObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
/**
* Gets the perf counter used for camera render time capture
*/
get: function () {
return this._cameraRenderTime;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
/**
* Gets the camera render time capture status
*/
get: function () {
return this._captureCameraRenderTime;
},
/**
* Enable or disable the camera render time capture
*/
set: function (value) {
var _this = this;
if (value === this._captureCameraRenderTime) {
return;
}
this._captureCameraRenderTime = value;
if (value) {
this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
_this._cameraRenderTime.beginMonitoring();
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Rendering camera " + camera.name);
});
this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
_this._cameraRenderTime.endMonitoring(false);
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Rendering camera " + camera.name);
});
}
else {
this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
this._onBeforeCameraRenderObserver = null;
this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
this._onAfterCameraRenderObserver = null;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
/**
* Gets the perf counter used for draw calls
*/
get: function () {
return this.scene.getEngine()._drawCalls;
},
enumerable: false,
configurable: true
});
/**
* Dispose and release associated resources.
*/
SceneInstrumentation.prototype.dispose = function () {
this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
this._onAfterRenderObserver = null;
this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
this._onBeforeActiveMeshesEvaluationObserver = null;
this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
this._onAfterActiveMeshesEvaluationObserver = null;
this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
this._onBeforeRenderTargetsRenderObserver = null;
this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
this._onAfterRenderTargetsRenderObserver = null;
this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
this._onBeforeAnimationsObserver = null;
this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
this._onBeforeParticlesRenderingObserver = null;
this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
this._onAfterParticlesRenderingObserver = null;
if (this._onBeforeSpritesRenderingObserver) {
this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
this._onBeforeSpritesRenderingObserver = null;
}
if (this._onAfterSpritesRenderingObserver) {
this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
this._onAfterSpritesRenderingObserver = null;
}
this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
this._onBeforeDrawPhaseObserver = null;
this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
this._onAfterDrawPhaseObserver = null;
if (this._onBeforePhysicsObserver) {
this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
this._onBeforePhysicsObserver = null;
}
if (this._onAfterPhysicsObserver) {
this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
this._onAfterPhysicsObserver = null;
}
this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
this._onAfterAnimationsObserver = null;
this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
this._onBeforeCameraRenderObserver = null;
this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
this._onAfterCameraRenderObserver = null;
this.scene = null;
};
return SceneInstrumentation;
}());
/***/ }),
/***/ "./Instrumentation/timeToken.ts":
/*!**************************************!*\
!*** ./Instrumentation/timeToken.ts ***!
\**************************************/
/*! exports provided: _TimeToken */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _TimeToken; });
/**
* @hidden
**/
var _TimeToken = /** @class */ (function () {
function _TimeToken() {
this._timeElapsedQueryEnded = false;
}
return _TimeToken;
}());
/***/ }),
/***/ "./Layers/effectLayer.ts":
/*!*******************************!*\
!*** ./Layers/effectLayer.ts ***!
\*******************************/
/*! exports provided: EffectLayer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return EffectLayer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Materials/materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Shaders_glowMapGeneration_fragment__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Shaders/glowMapGeneration.fragment */ "./Shaders/glowMapGeneration.fragment.ts");
/* harmony import */ var _Shaders_glowMapGeneration_vertex__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Shaders/glowMapGeneration.vertex */ "./Shaders/glowMapGeneration.vertex.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _Materials_effectFallbacks__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Materials/effectFallbacks */ "./Materials/effectFallbacks.ts");
/**
* The effect layer Helps adding post process effect blended with the main pass.
*
* This can be for instance use to generate glow or higlight effects on the scene.
*
* The effect layer class can not be used directly and is intented to inherited from to be
* customized per effects.
*/
var EffectLayer = /** @class */ (function () {
/**
* Instantiates a new effect Layer and references it in the scene.
* @param name The name of the layer
* @param scene The scene to use the layer in
*/
function EffectLayer(
/** The Friendly of the effect in the scene */
name, scene) {
this._vertexBuffers = {};
this._maxSize = 0;
this._mainTextureDesiredSize = { width: 0, height: 0 };
this._shouldRender = true;
this._postProcesses = [];
this._textures = [];
this._emissiveTextureAndColor = { texture: null, color: new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color4"]() };
/**
* The clear color of the texture used to generate the glow map.
*/
this.neutralColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color4"]();
/**
* Specifies whether the highlight layer is enabled or not.
*/
this.isEnabled = true;
/**
* An event triggered when the effect layer has been disposed.
*/
this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* An event triggered when the effect layer is about rendering the main texture with the glowy parts.
*/
this.onBeforeRenderMainTextureObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* An event triggered when the generated texture is being merged in the scene.
*/
this.onBeforeComposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* An event triggered when the mesh is rendered into the effect render target.
*/
this.onBeforeRenderMeshToEffect = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* An event triggered after the mesh has been rendered into the effect render target.
*/
this.onAfterRenderMeshToEffect = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* An event triggered when the generated texture has been merged in the scene.
*/
this.onAfterComposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
/**
* An event triggered when the efffect layer changes its size.
*/
this.onSizeChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_3__["Observable"]();
this.name = name;
this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_6__["EngineStore"].LastCreatedScene;
EffectLayer._SceneComponentInitialization(this._scene);
this._engine = this._scene.getEngine();
this._maxSize = this._engine.getCaps().maxTextureSize;
this._scene.effectLayers.push(this);
// Generate Buffers
this._generateIndexBuffer();
this._generateVertexBuffer();
}
Object.defineProperty(EffectLayer.prototype, "camera", {
/**
* Gets the camera attached to the layer.
*/
get: function () {
return this._effectLayerOptions.camera;
},
enumerable: false,
configurable: true
});
Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
/**
* Gets the rendering group id the layer should render in.
*/
get: function () {
return this._effectLayerOptions.renderingGroupId;
},
set: function (renderingGroupId) {
this._effectLayerOptions.renderingGroupId = renderingGroupId;
},
enumerable: false,
configurable: true
});
/**
* Initializes the effect layer with the required options.
* @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
*/
EffectLayer.prototype._init = function (options) {
// Adapt options
this._effectLayerOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ mainTextureRatio: 0.5, alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
this._setMainTextureSize();
this._createMainTexture();
this._createTextureAndPostProcesses();
this._mergeEffect = this._createMergeEffect();
};
/**
* Generates the index buffer of the full screen quad blending to the main canvas.
*/
EffectLayer.prototype._generateIndexBuffer = function () {
// Indices
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = this._engine.createIndexBuffer(indices);
};
/**
* Generates the vertex buffer of the full screen quad blending to the main canvas.
*/
EffectLayer.prototype._generateVertexBuffer = function () {
// VBO
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
var vertexBuffer = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"](this._engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind, false, false, 2);
this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind] = vertexBuffer;
};
/**
* Sets the main texture desired size which is the closest power of two
* of the engine canvas size.
*/
EffectLayer.prototype._setMainTextureSize = function () {
if (this._effectLayerOptions.mainTextureFixedSize) {
this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
}
else {
this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? _Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? _Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
}
this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
};
/**
* Creates the main texture for the effect layer.
*/
EffectLayer.prototype._createMainTexture = function () {
var _this = this;
this._mainTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_9__["RenderTargetTexture"]("HighlightLayerMainRTT", {
width: this._mainTextureDesiredSize.width,
height: this._mainTextureDesiredSize.height
}, this._scene, false, true, _Engines_constants__WEBPACK_IMPORTED_MODULE_12__["Constants"].TEXTURETYPE_UNSIGNED_INT);
this._mainTexture.activeCamera = this._effectLayerOptions.camera;
this._mainTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_8__["Texture"].CLAMP_ADDRESSMODE;
this._mainTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_8__["Texture"].CLAMP_ADDRESSMODE;
this._mainTexture.anisotropicFilteringLevel = 1;
this._mainTexture.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_8__["Texture"].BILINEAR_SAMPLINGMODE);
this._mainTexture.renderParticles = false;
this._mainTexture.renderList = null;
this._mainTexture.ignoreCameraViewport = true;
// Custom render function
this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
_this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
var index;
var engine = _this._scene.getEngine();
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
_this._renderSubMesh(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(true);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
_this._renderSubMesh(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
_this._renderSubMesh(alphaTestSubMeshes.data[index]);
}
var previousAlphaMode = engine.getAlphaMode();
for (index = 0; index < transparentSubMeshes.length; index++) {
_this._renderSubMesh(transparentSubMeshes.data[index], true);
}
engine.setAlphaMode(previousAlphaMode);
};
this._mainTexture.onClearObservable.add(function (engine) {
engine.clear(_this.neutralColor, true, true, true);
});
};
/**
* Adds specific effects defines.
* @param defines The defines to add specifics to.
*/
EffectLayer.prototype._addCustomEffectDefines = function (defines) {
// Nothing to add by default.
};
/**
* Checks for the readiness of the element composing the layer.
* @param subMesh the mesh to check for
* @param useInstances specify whether or not to use instances to render the mesh
* @param emissiveTexture the associated emissive texture used to generate the glow
* @return true if ready otherwise, false
*/
EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
var material = subMesh.getMaterial();
if (!material) {
return false;
}
if (!material.isReadyForSubMesh(subMesh.getMesh(), subMesh, useInstances)) {
return false;
}
var defines = [];
var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind];
var mesh = subMesh.getMesh();
var uv1 = false;
var uv2 = false;
// Diffuse
if (material) {
var needAlphaTest = material.needAlphaTesting();
var diffuseTexture = material.getAlphaTestTexture();
var needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
(material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);
if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
defines.push("#define DIFFUSE");
if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind) &&
diffuseTexture.coordinatesIndex === 1) {
defines.push("#define DIFFUSEUV2");
uv2 = true;
}
else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind)) {
defines.push("#define DIFFUSEUV1");
uv1 = true;
}
if (needAlphaTest) {
defines.push("#define ALPHATEST");
defines.push("#define ALPHATESTVALUE 0.4");
}
}
var opacityTexture = material.opacityTexture;
if (opacityTexture) {
defines.push("#define OPACITY");
if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind) &&
opacityTexture.coordinatesIndex === 1) {
defines.push("#define OPACITYUV2");
uv2 = true;
}
else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind)) {
defines.push("#define OPACITYUV1");
uv1 = true;
}
}
}
// Emissive
if (emissiveTexture) {
defines.push("#define EMISSIVE");
if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind) &&
emissiveTexture.coordinatesIndex === 1) {
defines.push("#define EMISSIVEUV2");
uv2 = true;
}
else if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind)) {
defines.push("#define EMISSIVEUV1");
uv1 = true;
}
}
// Vertex
if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].ColorKind) && mesh.hasVertexAlpha) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].ColorKind);
defines.push("#define VERTEXALPHA");
}
if (uv1) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind);
defines.push("#define UV1");
}
if (uv2) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind);
defines.push("#define UV2");
}
// Bones
var fallbacks = new _Materials_effectFallbacks__WEBPACK_IMPORTED_MODULE_16__["EffectFallbacks"]();
if (mesh.useBones && mesh.computeBonesUsingShaders) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].MatricesIndicesKind);
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].MatricesWeightsKind);
if (mesh.numBoneInfluencers > 4) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].MatricesIndicesExtraKind);
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].MatricesWeightsExtraKind);
}
defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
var skeleton = mesh.skeleton;
if (skeleton && skeleton.isUsingTextureForMatrices) {
defines.push("#define BONETEXTURE");
}
else {
defines.push("#define BonesPerMesh " + (skeleton ? (skeleton.bones.length + 1) : 0));
}
if (mesh.numBoneInfluencers > 0) {
fallbacks.addCPUSkinningFallback(0, mesh);
}
}
else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
// Morph targets
var manager = mesh.morphTargetManager;
var morphInfluencers = 0;
if (manager) {
if (manager.numInfluencers > 0) {
defines.push("#define MORPHTARGETS");
morphInfluencers = manager.numInfluencers;
defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_11__["MaterialHelper"].PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
}
}
// Instances
if (useInstances) {
defines.push("#define INSTANCES");
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_11__["MaterialHelper"].PushAttributesForInstances(attribs);
if (subMesh.getRenderingMesh().hasThinInstances) {
defines.push("#define THIN_INSTANCES");
}
}
this._addCustomEffectDefines(defines);
// Get correct effect
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection",
"glowColor", "morphTargetInfluences", "boneTextureWidth",
"diffuseMatrix", "emissiveMatrix", "opacityMatrix", "opacityIntensity"], ["diffuseSampler", "emissiveSampler", "opacitySampler", "boneSampler"], join, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
}
return this._effectLayerMapGenerationEffect.isReady();
};
/**
* Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
*/
EffectLayer.prototype.render = function () {
var currentEffect = this._mergeEffect;
// Check
if (!currentEffect.isReady()) {
return;
}
for (var i = 0; i < this._postProcesses.length; i++) {
if (!this._postProcesses[i].isReady()) {
return;
}
}
var engine = this._scene.getEngine();
this.onBeforeComposeObservable.notifyObservers(this);
// Render
engine.enableEffect(currentEffect);
engine.setState(false);
// VBOs
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
// Cache
var previousAlphaMode = engine.getAlphaMode();
// Go Blend.
engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
// Blends the map on the main canvas.
this._internalRender(currentEffect);
// Restore Alpha
engine.setAlphaMode(previousAlphaMode);
this.onAfterComposeObservable.notifyObservers(this);
// Handle size changes.
var size = this._mainTexture.getSize();
this._setMainTextureSize();
if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
// Recreate RTT and post processes on size change.
this.onSizeChangedObservable.notifyObservers(this);
this._disposeTextureAndPostProcesses();
this._createMainTexture();
this._createTextureAndPostProcesses();
}
};
/**
* Determine if a given mesh will be used in the current effect.
* @param mesh mesh to test
* @returns true if the mesh will be used
*/
EffectLayer.prototype.hasMesh = function (mesh) {
if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
return true;
}
return false;
};
/**
* Returns true if the layer contains information to display, otherwise false.
* @returns true if the glow layer should be rendered
*/
EffectLayer.prototype.shouldRender = function () {
return this.isEnabled && this._shouldRender;
};
/**
* Returns true if the mesh should render, otherwise false.
* @param mesh The mesh to render
* @returns true if it should render otherwise false
*/
EffectLayer.prototype._shouldRenderMesh = function (mesh) {
return true;
};
/**
* Returns true if the mesh can be rendered, otherwise false.
* @param mesh The mesh to render
* @param material The material used on the mesh
* @returns true if it can be rendered otherwise false
*/
EffectLayer.prototype._canRenderMesh = function (mesh, material) {
return !material.needAlphaBlendingForMesh(mesh);
};
/**
* Returns true if the mesh should render, otherwise false.
* @param mesh The mesh to render
* @returns true if it should render otherwise false
*/
EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function () {
return true;
};
/**
* Renders the submesh passed in parameter to the generation map.
*/
EffectLayer.prototype._renderSubMesh = function (subMesh, enableAlphaMode) {
var _this = this;
var _a;
if (enableAlphaMode === void 0) { enableAlphaMode = false; }
if (!this.shouldRender()) {
return;
}
var material = subMesh.getMaterial();
var ownerMesh = subMesh.getMesh();
var replacementMesh = subMesh.getReplacementMesh();
var renderingMesh = subMesh.getRenderingMesh();
var effectiveMesh = subMesh.getEffectiveMesh();
var scene = this._scene;
var engine = scene.getEngine();
effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
if (!material) {
return;
}
// Do not block in blend mode.
if (!this._canRenderMesh(renderingMesh, material)) {
return;
}
// Culling
var sideOrientation = (_a = renderingMesh.overrideMaterialSideOrientation) !== null && _a !== void 0 ? _a : material.sideOrientation;
var mainDeterminant = renderingMesh._getWorldMatrixDeterminant();
if (mainDeterminant < 0) {
sideOrientation = (sideOrientation === _Materials_material__WEBPACK_IMPORTED_MODULE_10__["Material"].ClockWiseSideOrientation ? _Materials_material__WEBPACK_IMPORTED_MODULE_10__["Material"].CounterClockWiseSideOrientation : _Materials_material__WEBPACK_IMPORTED_MODULE_10__["Material"].ClockWiseSideOrientation);
}
var reverse = sideOrientation === _Materials_material__WEBPACK_IMPORTED_MODULE_10__["Material"].ClockWiseSideOrientation;
engine.setState(material.backFaceCulling, material.zOffset, undefined, reverse);
// Managing instances
var batch = renderingMesh._getInstancesRenderList(subMesh._id, !!replacementMesh);
if (batch.mustReturn) {
return;
}
// Early Exit per mesh
if (!this._shouldRenderMesh(renderingMesh)) {
return;
}
var hardwareInstancedRendering = batch.hardwareInstancedRendering[subMesh._id] || renderingMesh.hasThinInstances;
this._setEmissiveTextureAndColor(renderingMesh, subMesh, material);
this.onBeforeRenderMeshToEffect.notifyObservers(ownerMesh);
if (this._useMeshMaterial(renderingMesh)) {
renderingMesh.render(subMesh, hardwareInstancedRendering, replacementMesh || undefined);
}
else if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
engine.enableEffect(this._effectLayerMapGenerationEffect);
renderingMesh._bind(subMesh, this._effectLayerMapGenerationEffect, _Materials_material__WEBPACK_IMPORTED_MODULE_10__["Material"].TriangleFillMode);
this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
this._effectLayerMapGenerationEffect.setMatrix("world", effectiveMesh.getWorldMatrix());
this._effectLayerMapGenerationEffect.setFloat4("glowColor", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
var needAlphaTest = material.needAlphaTesting();
var diffuseTexture = material.getAlphaTestTexture();
var needAlphaBlendFromDiffuse = diffuseTexture && diffuseTexture.hasAlpha &&
(material.useAlphaFromDiffuseTexture || material._useAlphaFromAlbedoTexture);
if (diffuseTexture && (needAlphaTest || needAlphaBlendFromDiffuse)) {
this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", diffuseTexture);
var textureMatrix = diffuseTexture.getTextureMatrix();
if (textureMatrix) {
this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
}
}
var opacityTexture = material.opacityTexture;
if (opacityTexture) {
this._effectLayerMapGenerationEffect.setTexture("opacitySampler", opacityTexture);
this._effectLayerMapGenerationEffect.setFloat("opacityIntensity", opacityTexture.level);
var textureMatrix = opacityTexture.getTextureMatrix();
if (textureMatrix) {
this._effectLayerMapGenerationEffect.setMatrix("opacityMatrix", textureMatrix);
}
}
// Glow emissive only
if (this._emissiveTextureAndColor.texture) {
this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
}
// Bones
if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
var skeleton = renderingMesh.skeleton;
if (skeleton.isUsingTextureForMatrices) {
var boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
if (!boneTexture) {
return;
}
this._effectLayerMapGenerationEffect.setTexture("boneSampler", boneTexture);
this._effectLayerMapGenerationEffect.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
}
else {
this._effectLayerMapGenerationEffect.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
}
}
// Morph targets
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_11__["MaterialHelper"].BindMorphTargetParameters(renderingMesh, this._effectLayerMapGenerationEffect);
// Alpha mode
if (enableAlphaMode) {
engine.setAlphaMode(material.alphaMode);
}
// Draw
renderingMesh._processRendering(effectiveMesh, subMesh, this._effectLayerMapGenerationEffect, material.fillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
}
else {
// Need to reset refresh rate of the main map
this._mainTexture.resetRefreshCounter();
}
this.onAfterRenderMeshToEffect.notifyObservers(ownerMesh);
};
/**
* Defines whether the current material of the mesh should be use to render the effect.
* @param mesh defines the current mesh to render
*/
EffectLayer.prototype._useMeshMaterial = function (mesh) {
return false;
};
/**
* Rebuild the required buffers.
* @hidden Internal use only.
*/
EffectLayer.prototype._rebuild = function () {
var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind];
if (vb) {
vb._rebuild();
}
this._generateIndexBuffer();
};
/**
* Dispose only the render target textures and post process.
*/
EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
this._mainTexture.dispose();
for (var i = 0; i < this._postProcesses.length; i++) {
if (this._postProcesses[i]) {
this._postProcesses[i].dispose();
}
}
this._postProcesses = [];
for (var i = 0; i < this._textures.length; i++) {
if (this._textures[i]) {
this._textures[i].dispose();
}
}
this._textures = [];
};
/**
* Dispose the highlight layer and free resources.
*/
EffectLayer.prototype.dispose = function () {
var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
// Clean textures and post processes
this._disposeTextureAndPostProcesses();
// Remove from scene
var index = this._scene.effectLayers.indexOf(this, 0);
if (index > -1) {
this._scene.effectLayers.splice(index, 1);
}
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onBeforeRenderMainTextureObservable.clear();
this.onBeforeComposeObservable.clear();
this.onBeforeRenderMeshToEffect.clear();
this.onAfterRenderMeshToEffect.clear();
this.onAfterComposeObservable.clear();
this.onSizeChangedObservable.clear();
};
/**
* Gets the class name of the effect layer
* @returns the string with the class name of the effect layer
*/
EffectLayer.prototype.getClassName = function () {
return "EffectLayer";
};
/**
* Creates an effect layer from parsed effect layer data
* @param parsedEffectLayer defines effect layer data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing the effect layer information
* @returns a parsed effect Layer
*/
EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
var effectLayerType = _Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Instantiate(parsedEffectLayer.customType);
return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
};
/** @hidden */
EffectLayer._SceneComponentInitialization = function (_) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_15__["_DevTools"].WarnImport("EffectLayerSceneComponent");
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], EffectLayer.prototype, "name", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor4"])()
], EffectLayer.prototype, "neutralColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], EffectLayer.prototype, "isEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsCameraReference"])()
], EffectLayer.prototype, "camera", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], EffectLayer.prototype, "renderingGroupId", null);
return EffectLayer;
}());
/***/ }),
/***/ "./Layers/effectLayerSceneComponent.ts":
/*!*********************************************!*\
!*** ./Layers/effectLayerSceneComponent.ts ***!
\*********************************************/
/*! exports provided: EffectLayerSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return EffectLayerSceneComponent; });
/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Cameras/camera */ "./Cameras/camera.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts");
/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts");
// Adds the parser to the scene parsers.
_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
if (parsedData.effectLayers) {
if (!container.effectLayers) {
container.effectLayers = new Array();
}
for (var index = 0; index < parsedData.effectLayers.length; index++) {
var effectLayer = _effectLayer__WEBPACK_IMPORTED_MODULE_2__["EffectLayer"].Parse(parsedData.effectLayers[index], scene, rootUrl);
container.effectLayers.push(effectLayer);
}
}
});
_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].prototype.removeEffectLayer = function (toRemove) {
var index = this.effectLayers.indexOf(toRemove);
if (index !== -1) {
this.effectLayers.splice(index, 1);
}
return index;
};
_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].prototype.addEffectLayer = function (newEffectLayer) {
this.effectLayers.push(newEffectLayer);
};
/**
* Defines the layer scene component responsible to manage any effect layers
* in a given scene.
*/
var EffectLayerSceneComponent = /** @class */ (function () {
/**
* Creates a new instance of the component for the given scene
* @param scene Defines the scene to register the component in
*/
function EffectLayerSceneComponent(scene) {
/**
* The component name helpfull to identify the component in the list of scene components.
*/
this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER;
this._renderEffects = false;
this._needStencil = false;
this._previousStencilState = false;
this.scene = scene;
this._engine = scene.getEngine();
scene.effectLayers = new Array();
}
/**
* Registers the component in a given scene
*/
EffectLayerSceneComponent.prototype.register = function () {
this.scene._isReadyForMeshStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
this.scene._cameraDrawRenderTargetStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
this.scene._beforeCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
this.scene._afterRenderingGroupDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
EffectLayerSceneComponent.prototype.rebuild = function () {
var layers = this.scene.effectLayers;
for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
var effectLayer = layers_1[_i];
effectLayer._rebuild();
}
};
/**
* Serializes the component data to the specified json object
* @param serializationObject The object to serialize to
*/
EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
// Effect layers
serializationObject.effectLayers = [];
var layers = this.scene.effectLayers;
for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
var effectLayer = layers_2[_i];
if (effectLayer.serialize) {
serializationObject.effectLayers.push(effectLayer.serialize());
}
}
};
/**
* Adds all the elements from the container to the scene
* @param container the container holding the elements
*/
EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
var _this = this;
if (!container.effectLayers) {
return;
}
container.effectLayers.forEach(function (o) {
_this.scene.addEffectLayer(o);
});
};
/**
* Removes all the elements in the container from the scene
* @param container contains the elements to remove
* @param dispose if the removed element should be disposed (default: false)
*/
EffectLayerSceneComponent.prototype.removeFromContainer = function (container, dispose) {
var _this = this;
if (!container.effectLayers) {
return;
}
container.effectLayers.forEach(function (o) {
_this.scene.removeEffectLayer(o);
if (dispose) {
o.dispose();
}
});
};
/**
* Disposes the component and the associated ressources.
*/
EffectLayerSceneComponent.prototype.dispose = function () {
var layers = this.scene.effectLayers;
while (layers.length) {
layers[0].dispose();
}
};
EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
var layers = this.scene.effectLayers;
for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
var layer = layers_3[_i];
if (!layer.hasMesh(mesh)) {
continue;
}
for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
var subMesh = _b[_a];
if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
return false;
}
}
}
return true;
};
EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
this._renderEffects = false;
this._needStencil = false;
var needRebind = false;
var layers = this.scene.effectLayers;
if (layers && layers.length > 0) {
this._previousStencilState = this._engine.getStencilBuffer();
for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
var effectLayer = layers_4[_i];
if (effectLayer.shouldRender() &&
(!effectLayer.camera ||
(effectLayer.camera.cameraRigMode === _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_NONE && camera === effectLayer.camera) ||
(effectLayer.camera.cameraRigMode !== _Cameras_camera__WEBPACK_IMPORTED_MODULE_0__["Camera"].RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
this._renderEffects = true;
this._needStencil = this._needStencil || effectLayer.needStencil();
var renderTarget = effectLayer._mainTexture;
if (renderTarget._shouldRender()) {
this.scene.incrementRenderId();
renderTarget.render(false, false);
needRebind = true;
}
}
}
this.scene.incrementRenderId();
}
return needRebind;
};
EffectLayerSceneComponent.prototype._setStencil = function () {
// Activate effect Layer stencil
if (this._needStencil) {
this._engine.setStencilBuffer(true);
}
};
EffectLayerSceneComponent.prototype._setStencilBack = function () {
// Restore effect Layer stencil
if (this._needStencil) {
this._engine.setStencilBuffer(this._previousStencilState);
}
};
EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
if (this._renderEffects) {
this._engine.setDepthBuffer(false);
var layers = this.scene.effectLayers;
for (var i = 0; i < layers.length; i++) {
var effectLayer = layers[i];
if (effectLayer.renderingGroupId === renderingGroupId) {
if (effectLayer.shouldRender()) {
effectLayer.render();
}
}
}
this._engine.setDepthBuffer(true);
}
};
EffectLayerSceneComponent.prototype._drawCamera = function () {
if (this._renderEffects) {
this._draw(-1);
}
};
EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
this._draw(index);
}
};
return EffectLayerSceneComponent;
}());
_effectLayer__WEBPACK_IMPORTED_MODULE_2__["EffectLayer"]._SceneComponentInitialization = function (scene) {
var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_EFFECTLAYER);
if (!component) {
component = new EffectLayerSceneComponent(scene);
scene._addComponent(component);
}
};
/***/ }),
/***/ "./Layers/glowLayer.ts":
/*!*****************************!*\
!*** ./Layers/glowLayer.ts ***!
\*****************************/
/*! exports provided: GlowLayer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return GlowLayer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts");
/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts");
/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Shaders_glowMapMerge_fragment__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Shaders/glowMapMerge.fragment */ "./Shaders/glowMapMerge.fragment.ts");
/* harmony import */ var _Shaders_glowMapMerge_vertex__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Shaders/glowMapMerge.vertex */ "./Shaders/glowMapMerge.vertex.ts");
/* harmony import */ var _Layers_effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Layers/effectLayerSceneComponent */ "./Layers/effectLayerSceneComponent.ts");
_abstractScene__WEBPACK_IMPORTED_MODULE_9__["AbstractScene"].prototype.getGlowLayerByName = function (name) {
for (var index = 0; index < this.effectLayers.length; index++) {
if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
return this.effectLayers[index];
}
}
return null;
};
/**
* The glow layer Helps adding a glow effect around the emissive parts of a mesh.
*
* Once instantiated in a scene, by default, all the emissive meshes will glow.
*
* Documentation: https://doc.babylonjs.com/how_to/glow_layer
*/
var GlowLayer = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GlowLayer, _super);
/**
* Instantiates a new glow Layer and references it to the scene.
* @param name The name of the layer
* @param scene The scene to use the layer in
* @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
*/
function GlowLayer(name, scene, options) {
var _this = _super.call(this, name, scene) || this;
_this._intensity = 1.0;
_this._includedOnlyMeshes = [];
_this._excludedMeshes = [];
_this._meshesUsingTheirOwnMaterials = [];
_this.neutralColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color4"](0, 0, 0, 1);
// Adapt options
_this._options = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
// Initialize the layer
_this._init({
alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].ALPHA_ADD,
camera: _this._options.camera,
mainTextureFixedSize: _this._options.mainTextureFixedSize,
mainTextureRatio: _this._options.mainTextureRatio,
renderingGroupId: _this._options.renderingGroupId
});
return _this;
}
Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
/**
* Gets the kernel size of the blur.
*/
get: function () {
return this._horizontalBlurPostprocess1.kernel;
},
/**
* Sets the kernel size of the blur.
*/
set: function (value) {
this._horizontalBlurPostprocess1.kernel = value;
this._verticalBlurPostprocess1.kernel = value;
this._horizontalBlurPostprocess2.kernel = value;
this._verticalBlurPostprocess2.kernel = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(GlowLayer.prototype, "intensity", {
/**
* Gets the glow intensity.
*/
get: function () {
return this._intensity;
},
/**
* Sets the glow intensity.
*/
set: function (value) {
this._intensity = value;
},
enumerable: false,
configurable: true
});
/**
* Get the effect name of the layer.
* @return The effect name
*/
GlowLayer.prototype.getEffectName = function () {
return GlowLayer.EffectName;
};
/**
* Create the merge effect. This is the shader use to blit the information back
* to the main canvas at the end of the scene rendering.
*/
GlowLayer.prototype._createMergeEffect = function () {
// Effect
return this._engine.createEffect("glowMapMerge", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
};
/**
* Creates the render target textures and post processes used in the glow layer.
*/
GlowLayer.prototype._createTextureAndPostProcesses = function () {
var _this = this;
var blurTextureWidth = this._mainTextureDesiredSize.width;
var blurTextureHeight = this._mainTextureDesiredSize.height;
blurTextureWidth = this._engine.needPOTTextures ? _Engines_engine__WEBPACK_IMPORTED_MODULE_12__["Engine"].GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
blurTextureHeight = this._engine.needPOTTextures ? _Engines_engine__WEBPACK_IMPORTED_MODULE_12__["Engine"].GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
var textureType = 0;
if (this._engine.getCaps().textureHalfFloatRender) {
textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT;
}
else {
textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT;
}
this._blurTexture1 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_5__["RenderTargetTexture"]("GlowLayerBlurRTT", {
width: blurTextureWidth,
height: blurTextureHeight
}, this._scene, false, true, textureType);
this._blurTexture1.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE;
this._blurTexture1.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE;
this._blurTexture1.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].BILINEAR_SAMPLINGMODE);
this._blurTexture1.renderParticles = false;
this._blurTexture1.ignoreCameraViewport = true;
var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
this._blurTexture2 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_5__["RenderTargetTexture"]("GlowLayerBlurRTT2", {
width: blurTextureWidth2,
height: blurTextureHeight2
}, this._scene, false, true, textureType);
this._blurTexture2.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE;
this._blurTexture2.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].CLAMP_ADDRESSMODE;
this._blurTexture2.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].BILINEAR_SAMPLINGMODE);
this._blurTexture2.renderParticles = false;
this._blurTexture2.ignoreCameraViewport = true;
this._textures = [this._blurTexture1, this._blurTexture2];
this._horizontalBlurPostprocess1 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_7__["BlurPostProcess"]("GlowLayerHBP1", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](1.0, 0), this._options.blurKernelSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess1.width = blurTextureWidth;
this._horizontalBlurPostprocess1.height = blurTextureHeight;
this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
effect.setTexture("textureSampler", _this._mainTexture);
});
this._verticalBlurPostprocess1 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_7__["BlurPostProcess"]("GlowLayerVBP1", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 1.0), this._options.blurKernelSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess2 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_7__["BlurPostProcess"]("GlowLayerHBP2", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](1.0, 0), this._options.blurKernelSize / 2, {
width: blurTextureWidth2,
height: blurTextureHeight2
}, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess2.width = blurTextureWidth2;
this._horizontalBlurPostprocess2.height = blurTextureHeight2;
this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
effect.setTexture("textureSampler", _this._blurTexture1);
});
this._verticalBlurPostprocess2 = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_7__["BlurPostProcess"]("GlowLayerVBP2", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector2"](0, 1.0), this._options.blurKernelSize / 2, {
width: blurTextureWidth2,
height: blurTextureHeight2
}, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_4__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
this._mainTexture.samples = this._options.mainTextureSamples;
this._mainTexture.onAfterUnbindObservable.add(function () {
var internalTexture = _this._blurTexture1.getInternalTexture();
if (internalTexture) {
_this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
var internalTexture2 = _this._blurTexture2.getInternalTexture();
if (internalTexture2) {
_this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture2, true);
}
_this._engine.unBindFramebuffer(internalTexture2 !== null && internalTexture2 !== void 0 ? internalTexture2 : internalTexture, true);
}
});
// Prevent autoClear.
this._postProcesses.map(function (pp) { pp.autoClear = false; });
};
/**
* Checks for the readiness of the element composing the layer.
* @param subMesh the mesh to check for
* @param useInstances specify wether or not to use instances to render the mesh
* @param emissiveTexture the associated emissive texture used to generate the glow
* @return true if ready otherwise, false
*/
GlowLayer.prototype.isReady = function (subMesh, useInstances) {
var material = subMesh.getMaterial();
var mesh = subMesh.getRenderingMesh();
if (!material || !mesh) {
return false;
}
var emissiveTexture = material.emissiveTexture;
return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
};
/**
* Returns whether or nood the layer needs stencil enabled during the mesh rendering.
*/
GlowLayer.prototype.needStencil = function () {
return false;
};
/**
* Returns true if the mesh can be rendered, otherwise false.
* @param mesh The mesh to render
* @param material The material used on the mesh
* @returns true if it can be rendered otherwise false
*/
GlowLayer.prototype._canRenderMesh = function (mesh, material) {
return true;
};
/**
* Implementation specific of rendering the generating effect on the main canvas.
* @param effect The effect used to render through
*/
GlowLayer.prototype._internalRender = function (effect) {
// Texture
effect.setTexture("textureSampler", this._blurTexture1);
effect.setTexture("textureSampler2", this._blurTexture2);
effect.setFloat("offset", this._intensity);
// Cache
var engine = this._engine;
var previousStencilBuffer = engine.getStencilBuffer();
// Draw order
engine.setStencilBuffer(false);
engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6);
// Draw order
engine.setStencilBuffer(previousStencilBuffer);
};
/**
* Sets the required values for both the emissive texture and and the main color.
*/
GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
var textureLevel = 1.0;
if (this.customEmissiveTextureSelector) {
this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
}
else {
if (material) {
this._emissiveTextureAndColor.texture = material.emissiveTexture;
if (this._emissiveTextureAndColor.texture) {
textureLevel = this._emissiveTextureAndColor.texture.level;
}
}
else {
this._emissiveTextureAndColor.texture = null;
}
}
if (this.customEmissiveColorSelector) {
this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
}
else {
if (material.emissiveColor) {
this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, material.alpha);
}
else {
this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
}
}
};
/**
* Returns true if the mesh should render, otherwise false.
* @param mesh The mesh to render
* @returns true if it should render otherwise false
*/
GlowLayer.prototype._shouldRenderMesh = function (mesh) {
return this.hasMesh(mesh);
};
/**
* Adds specific effects defines.
* @param defines The defines to add specifics to.
*/
GlowLayer.prototype._addCustomEffectDefines = function (defines) {
defines.push("#define GLOW");
};
/**
* Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
* @param mesh The mesh to exclude from the glow layer
*/
GlowLayer.prototype.addExcludedMesh = function (mesh) {
if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
this._excludedMeshes.push(mesh.uniqueId);
}
};
/**
* Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
* @param mesh The mesh to remove
*/
GlowLayer.prototype.removeExcludedMesh = function (mesh) {
var index = this._excludedMeshes.indexOf(mesh.uniqueId);
if (index !== -1) {
this._excludedMeshes.splice(index, 1);
}
};
/**
* Add a mesh in the inclusion list to impact or being impacted by the glow layer.
* @param mesh The mesh to include in the glow layer
*/
GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
this._includedOnlyMeshes.push(mesh.uniqueId);
}
};
/**
* Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
* @param mesh The mesh to remove
*/
GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
if (index !== -1) {
this._includedOnlyMeshes.splice(index, 1);
}
};
/**
* Determine if a given mesh will be used in the glow layer
* @param mesh The mesh to test
* @returns true if the mesh will be highlighted by the current glow layer
*/
GlowLayer.prototype.hasMesh = function (mesh) {
if (!_super.prototype.hasMesh.call(this, mesh)) {
return false;
}
// Included Mesh
if (this._includedOnlyMeshes.length) {
return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
}
// Excluded Mesh
if (this._excludedMeshes.length) {
return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
}
return true;
};
/**
* Defines whether the current material of the mesh should be use to render the effect.
* @param mesh defines the current mesh to render
*/
GlowLayer.prototype._useMeshMaterial = function (mesh) {
if (this._meshesUsingTheirOwnMaterials.length == 0) {
return false;
}
return this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId) > -1;
};
/**
* Add a mesh to be rendered through its own material and not with emissive only.
* @param mesh The mesh for which we need to use its material
*/
GlowLayer.prototype.referenceMeshToUseItsOwnMaterial = function (mesh) {
this._meshesUsingTheirOwnMaterials.push(mesh.uniqueId);
};
/**
* Remove a mesh from being rendered through its own material and not with emissive only.
* @param mesh The mesh for which we need to not use its material
*/
GlowLayer.prototype.unReferenceMeshFromUsingItsOwnMaterial = function (mesh) {
var index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);
while (index >= 0) {
this._meshesUsingTheirOwnMaterials.splice(index, 1);
index = this._meshesUsingTheirOwnMaterials.indexOf(mesh.uniqueId);
}
};
/**
* Free any resources and references associated to a mesh.
* Internal use
* @param mesh The mesh to free.
* @hidden
*/
GlowLayer.prototype._disposeMesh = function (mesh) {
this.removeIncludedOnlyMesh(mesh);
this.removeExcludedMesh(mesh);
};
/**
* Gets the class name of the effect layer
* @returns the string with the class name of the effect layer
*/
GlowLayer.prototype.getClassName = function () {
return "GlowLayer";
};
/**
* Serializes this glow layer
* @returns a serialized glow layer object
*/
GlowLayer.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.GlowLayer";
var index;
// Included meshes
serializationObject.includedMeshes = [];
if (this._includedOnlyMeshes.length) {
for (index = 0; index < this._includedOnlyMeshes.length; index++) {
var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
if (mesh) {
serializationObject.includedMeshes.push(mesh.id);
}
}
}
// Excluded meshes
serializationObject.excludedMeshes = [];
if (this._excludedMeshes.length) {
for (index = 0; index < this._excludedMeshes.length; index++) {
var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
if (mesh) {
serializationObject.excludedMeshes.push(mesh.id);
}
}
}
return serializationObject;
};
/**
* Creates a Glow Layer from parsed glow layer data
* @param parsedGlowLayer defines glow layer data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing the glow layer information
* @returns a parsed Glow Layer
*/
GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
var gl = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
var index;
// Excluded meshes
for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
if (mesh) {
gl.addExcludedMesh(mesh);
}
}
// Included meshes
for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
if (mesh) {
gl.addIncludedOnlyMesh(mesh);
}
}
return gl;
};
/**
* Effect Name of the layer.
*/
GlowLayer.EffectName = "GlowLayer";
/**
* The default blur kernel size used for the glow.
*/
GlowLayer.DefaultBlurKernelSize = 32;
/**
* The default texture size ratio used for the glow.
*/
GlowLayer.DefaultTextureRatio = 0.5;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], GlowLayer.prototype, "blurKernelSize", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], GlowLayer.prototype, "intensity", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("options")
], GlowLayer.prototype, "_options", void 0);
return GlowLayer;
}(_effectLayer__WEBPACK_IMPORTED_MODULE_8__["EffectLayer"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_11__["_TypeStore"].RegisteredTypes["BABYLON.GlowLayer"] = GlowLayer;
/***/ }),
/***/ "./Layers/highlightLayer.ts":
/*!**********************************!*\
!*** ./Layers/highlightLayer.ts ***!
\**********************************/
/*! exports provided: HighlightLayer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return HighlightLayer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts");
/* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts");
/* harmony import */ var _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../PostProcesses/passPostProcess */ "./PostProcesses/passPostProcess.ts");
/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts");
/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts");
/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Shaders_glowMapMerge_fragment__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../Shaders/glowMapMerge.fragment */ "./Shaders/glowMapMerge.fragment.ts");
/* harmony import */ var _Shaders_glowMapMerge_vertex__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../Shaders/glowMapMerge.vertex */ "./Shaders/glowMapMerge.vertex.ts");
/* harmony import */ var _Shaders_glowBlurPostProcess_fragment__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../Shaders/glowBlurPostProcess.fragment */ "./Shaders/glowBlurPostProcess.fragment.ts");
_abstractScene__WEBPACK_IMPORTED_MODULE_13__["AbstractScene"].prototype.getHighlightLayerByName = function (name) {
for (var index = 0; index < this.effectLayers.length; index++) {
if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
return this.effectLayers[index];
}
}
return null;
};
/**
* Special Glow Blur post process only blurring the alpha channel
* It enforces keeping the most luminous color in the color channel.
*/
var GlowBlurPostProcess = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GlowBlurPostProcess, _super);
function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
if (samplingMode === void 0) { samplingMode = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE; }
var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
_this.direction = direction;
_this.kernel = kernel;
_this.onApplyObservable.add(function (effect) {
effect.setFloat2("screenSize", _this.width, _this.height);
effect.setVector2("direction", _this.direction);
effect.setFloat("blurWidth", _this.kernel);
});
return _this;
}
return GlowBlurPostProcess;
}(_PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_9__["PostProcess"]));
/**
* The highlight layer Helps adding a glow effect around a mesh.
*
* Once instantiated in a scene, simply use the addMesh or removeMesh method to add or remove
* glowy meshes to your scene.
*
* !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
*/
var HighlightLayer = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(HighlightLayer, _super);
/**
* Instantiates a new highlight Layer and references it to the scene..
* @param name The name of the layer
* @param scene The scene to use the layer in
* @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
*/
function HighlightLayer(name, scene, options) {
var _this = _super.call(this, name, scene) || this;
_this.name = name;
/**
* Specifies whether or not the inner glow is ACTIVE in the layer.
*/
_this.innerGlow = true;
/**
* Specifies whether or not the outer glow is ACTIVE in the layer.
*/
_this.outerGlow = true;
/**
* An event triggered when the highlight layer is being blurred.
*/
_this.onBeforeBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* An event triggered when the highlight layer has been blurred.
*/
_this.onAfterBlurObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
_this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
_this._meshes = {};
_this._excludedMeshes = {};
_this.neutralColor = HighlightLayer.NeutralColor;
// Warn on stencil
if (!_this._engine.isStencilEnable) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_15__["Logger"].Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new Engine(canvas, antialias, { stencil: true }");
}
// Adapt options
_this._options = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
// Initialize the layer
_this._init({
alphaBlendingMode: _this._options.alphaBlendingMode,
camera: _this._options.camera,
mainTextureFixedSize: _this._options.mainTextureFixedSize,
mainTextureRatio: _this._options.mainTextureRatio,
renderingGroupId: _this._options.renderingGroupId
});
// Do not render as long as no meshes have been added
_this._shouldRender = false;
return _this;
}
Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
/**
* Gets the horizontal size of the blur.
*/
get: function () {
return this._horizontalBlurPostprocess.kernel;
},
/**
* Specifies the horizontal size of the blur.
*/
set: function (value) {
this._horizontalBlurPostprocess.kernel = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
/**
* Gets the vertical size of the blur.
*/
get: function () {
return this._verticalBlurPostprocess.kernel;
},
/**
* Specifies the vertical size of the blur.
*/
set: function (value) {
this._verticalBlurPostprocess.kernel = value;
},
enumerable: false,
configurable: true
});
/**
* Get the effect name of the layer.
* @return The effect name
*/
HighlightLayer.prototype.getEffectName = function () {
return HighlightLayer.EffectName;
};
/**
* Create the merge effect. This is the shader use to blit the information back
* to the main canvas at the end of the scene rendering.
*/
HighlightLayer.prototype._createMergeEffect = function () {
// Effect
return this._engine.createEffect("glowMapMerge", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
};
/**
* Creates the render target textures and post processes used in the highlight layer.
*/
HighlightLayer.prototype._createTextureAndPostProcesses = function () {
var _this = this;
var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
blurTextureWidth = this._engine.needPOTTextures ? _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
blurTextureHeight = this._engine.needPOTTextures ? _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
var textureType = 0;
if (this._engine.getCaps().textureHalfFloatRender) {
textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].TEXTURETYPE_HALF_FLOAT;
}
else {
textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].TEXTURETYPE_UNSIGNED_INT;
}
this._blurTexture = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_8__["RenderTargetTexture"]("HighlightLayerBlurRTT", {
width: blurTextureWidth,
height: blurTextureHeight
}, this._scene, false, true, textureType);
this._blurTexture.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE;
this._blurTexture.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].CLAMP_ADDRESSMODE;
this._blurTexture.anisotropicFilteringLevel = 16;
this._blurTexture.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].TRILINEAR_SAMPLINGMODE);
this._blurTexture.renderParticles = false;
this._blurTexture.ignoreCameraViewport = true;
this._textures = [this._blurTexture];
if (this._options.alphaBlendingMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].ALPHA_COMBINE) {
this._downSamplePostprocess = new _PostProcesses_passPostProcess__WEBPACK_IMPORTED_MODULE_10__["PassPostProcess"]("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine());
this._downSamplePostprocess.onApplyObservable.add(function (effect) {
effect.setTexture("textureSampler", _this._mainTexture);
});
this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1.0, 0), this._options.blurHorizontalSize, 1, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine());
this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
});
this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 1.0), this._options.blurVerticalSize, 1, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine());
this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
});
this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
}
else {
this._horizontalBlurPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__["BlurPostProcess"]("HighlightLayerHBP", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1.0, 0), this._options.blurHorizontalSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._horizontalBlurPostprocess.width = blurTextureWidth;
this._horizontalBlurPostprocess.height = blurTextureHeight;
this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
effect.setTexture("textureSampler", _this._mainTexture);
});
this._verticalBlurPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_11__["BlurPostProcess"]("HighlightLayerVBP", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](0, 1.0), this._options.blurVerticalSize / 2, {
width: blurTextureWidth,
height: blurTextureHeight
}, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
}
this._mainTexture.onAfterUnbindObservable.add(function () {
_this.onBeforeBlurObservable.notifyObservers(_this);
var internalTexture = _this._blurTexture.getInternalTexture();
if (internalTexture) {
_this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
_this._engine.unBindFramebuffer(internalTexture, true);
}
_this.onAfterBlurObservable.notifyObservers(_this);
});
// Prevent autoClear.
this._postProcesses.map(function (pp) { pp.autoClear = false; });
};
/**
* Returns wether or nood the layer needs stencil enabled during the mesh rendering.
*/
HighlightLayer.prototype.needStencil = function () {
return true;
};
/**
* Checks for the readiness of the element composing the layer.
* @param subMesh the mesh to check for
* @param useInstances specify wether or not to use instances to render the mesh
* @param emissiveTexture the associated emissive texture used to generate the glow
* @return true if ready otherwise, false
*/
HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
var material = subMesh.getMaterial();
var mesh = subMesh.getRenderingMesh();
if (!material || !mesh || !this._meshes) {
return false;
}
var emissiveTexture = null;
var highlightLayerMesh = this._meshes[mesh.uniqueId];
if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
emissiveTexture = material.emissiveTexture;
}
return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
};
/**
* Implementation specific of rendering the generating effect on the main canvas.
* @param effect The effect used to render through
*/
HighlightLayer.prototype._internalRender = function (effect) {
// Texture
effect.setTexture("textureSampler", this._blurTexture);
// Cache
var engine = this._engine;
engine.cacheStencilState();
// Stencil operations
engine.setStencilOperationPass(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].REPLACE);
engine.setStencilOperationFail(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].KEEP);
engine.setStencilOperationDepthFail(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].KEEP);
// Draw order
engine.setStencilMask(0x00);
engine.setStencilBuffer(true);
engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
// 2 passes inner outer
if (this.outerGlow) {
effect.setFloat("offset", 0);
engine.setStencilFunction(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].NOTEQUAL);
engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6);
}
if (this.innerGlow) {
effect.setFloat("offset", 1);
engine.setStencilFunction(_Engines_constants__WEBPACK_IMPORTED_MODULE_14__["Constants"].EQUAL);
engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6);
}
// Restore Cache
engine.restoreStencilState();
};
/**
* Returns true if the layer contains information to display, otherwise false.
*/
HighlightLayer.prototype.shouldRender = function () {
if (_super.prototype.shouldRender.call(this)) {
return this._meshes ? true : false;
}
return false;
};
/**
* Returns true if the mesh should render, otherwise false.
* @param mesh The mesh to render
* @returns true if it should render otherwise false
*/
HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
// Excluded Mesh
if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
return false;
}
if (!_super.prototype.hasMesh.call(this, mesh)) {
return false;
}
return true;
};
/**
* Returns true if the mesh can be rendered, otherwise false.
* @param mesh The mesh to render
* @param material The material used on the mesh
* @returns true if it can be rendered otherwise false
*/
HighlightLayer.prototype._canRenderMesh = function (mesh, material) {
// all meshes can be rendered in the highlight layer, even transparent ones
return true;
};
/**
* Adds specific effects defines.
* @param defines The defines to add specifics to.
*/
HighlightLayer.prototype._addCustomEffectDefines = function (defines) {
defines.push("#define HIGHLIGHT");
};
/**
* Sets the required values for both the emissive texture and and the main color.
*/
HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
var highlightLayerMesh = this._meshes[mesh.uniqueId];
if (highlightLayerMesh) {
this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
}
else {
this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
}
if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
this._emissiveTextureAndColor.texture = material.emissiveTexture;
this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
}
else {
this._emissiveTextureAndColor.texture = null;
}
};
/**
* Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
* @param mesh The mesh to exclude from the highlight layer
*/
HighlightLayer.prototype.addExcludedMesh = function (mesh) {
if (!this._excludedMeshes) {
return;
}
var meshExcluded = this._excludedMeshes[mesh.uniqueId];
if (!meshExcluded) {
this._excludedMeshes[mesh.uniqueId] = {
mesh: mesh,
beforeBind: mesh.onBeforeBindObservable.add(function (mesh) {
mesh.getEngine().setStencilBuffer(false);
}),
afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
mesh.getEngine().setStencilBuffer(true);
}),
};
}
};
/**
* Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
* @param mesh The mesh to highlight
*/
HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
if (!this._excludedMeshes) {
return;
}
var meshExcluded = this._excludedMeshes[mesh.uniqueId];
if (meshExcluded) {
if (meshExcluded.beforeBind) {
mesh.onBeforeBindObservable.remove(meshExcluded.beforeBind);
}
if (meshExcluded.afterRender) {
mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
}
}
this._excludedMeshes[mesh.uniqueId] = null;
};
/**
* Determine if a given mesh will be highlighted by the current HighlightLayer
* @param mesh mesh to test
* @returns true if the mesh will be highlighted by the current HighlightLayer
*/
HighlightLayer.prototype.hasMesh = function (mesh) {
if (!this._meshes) {
return false;
}
if (!_super.prototype.hasMesh.call(this, mesh)) {
return false;
}
return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
};
/**
* Add a mesh in the highlight layer in order to make it glow with the chosen color.
* @param mesh The mesh to highlight
* @param color The color of the highlight
* @param glowEmissiveOnly Extract the glow from the emissive texture
*/
HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
var _this = this;
if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
if (!this._meshes) {
return;
}
var meshHighlight = this._meshes[mesh.uniqueId];
if (meshHighlight) {
meshHighlight.color = color;
}
else {
this._meshes[mesh.uniqueId] = {
mesh: mesh,
color: color,
// Lambda required for capture due to Observable this context
observerHighlight: mesh.onBeforeBindObservable.add(function (mesh) {
if (_this.isEnabled) {
if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
_this._defaultStencilReference(mesh);
}
else {
mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
}
}
}),
observerDefault: mesh.onAfterRenderObservable.add(function (mesh) {
if (_this.isEnabled) {
_this._defaultStencilReference(mesh);
}
}),
glowEmissiveOnly: glowEmissiveOnly
};
mesh.onDisposeObservable.add(function () {
_this._disposeMesh(mesh);
});
}
this._shouldRender = true;
};
/**
* Remove a mesh from the highlight layer in order to make it stop glowing.
* @param mesh The mesh to highlight
*/
HighlightLayer.prototype.removeMesh = function (mesh) {
if (!this._meshes) {
return;
}
var meshHighlight = this._meshes[mesh.uniqueId];
if (meshHighlight) {
if (meshHighlight.observerHighlight) {
mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
}
if (meshHighlight.observerDefault) {
mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
}
delete this._meshes[mesh.uniqueId];
}
this._shouldRender = false;
for (var meshHighlightToCheck in this._meshes) {
if (this._meshes[meshHighlightToCheck]) {
this._shouldRender = true;
break;
}
}
};
/**
* Remove all the meshes currently referenced in the highlight layer
*/
HighlightLayer.prototype.removeAllMeshes = function () {
if (!this._meshes) {
return;
}
for (var uniqueId in this._meshes) {
if (this._meshes.hasOwnProperty(uniqueId)) {
var mesh = this._meshes[uniqueId];
if (mesh) {
this.removeMesh(mesh.mesh);
}
}
}
};
/**
* Force the stencil to the normal expected value for none glowing parts
*/
HighlightLayer.prototype._defaultStencilReference = function (mesh) {
mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
};
/**
* Free any resources and references associated to a mesh.
* Internal use
* @param mesh The mesh to free.
* @hidden
*/
HighlightLayer.prototype._disposeMesh = function (mesh) {
this.removeMesh(mesh);
this.removeExcludedMesh(mesh);
};
/**
* Dispose the highlight layer and free resources.
*/
HighlightLayer.prototype.dispose = function () {
if (this._meshes) {
// Clean mesh references
for (var id in this._meshes) {
var meshHighlight = this._meshes[id];
if (meshHighlight && meshHighlight.mesh) {
if (meshHighlight.observerHighlight) {
meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.observerHighlight);
}
if (meshHighlight.observerDefault) {
meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
}
}
}
this._meshes = null;
}
if (this._excludedMeshes) {
for (var id in this._excludedMeshes) {
var meshHighlight = this._excludedMeshes[id];
if (meshHighlight) {
if (meshHighlight.beforeBind) {
meshHighlight.mesh.onBeforeBindObservable.remove(meshHighlight.beforeBind);
}
if (meshHighlight.afterRender) {
meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
}
}
}
this._excludedMeshes = null;
}
_super.prototype.dispose.call(this);
};
/**
* Gets the class name of the effect layer
* @returns the string with the class name of the effect layer
*/
HighlightLayer.prototype.getClassName = function () {
return "HighlightLayer";
};
/**
* Serializes this Highlight layer
* @returns a serialized Highlight layer object
*/
HighlightLayer.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.HighlightLayer";
// Highlighted meshes
serializationObject.meshes = [];
if (this._meshes) {
for (var m in this._meshes) {
var mesh = this._meshes[m];
if (mesh) {
serializationObject.meshes.push({
glowEmissiveOnly: mesh.glowEmissiveOnly,
color: mesh.color.asArray(),
meshId: mesh.mesh.id
});
}
}
}
// Excluded meshes
serializationObject.excludedMeshes = [];
if (this._excludedMeshes) {
for (var e in this._excludedMeshes) {
var excludedMesh = this._excludedMeshes[e];
if (excludedMesh) {
serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
}
}
}
return serializationObject;
};
/**
* Creates a Highlight layer from parsed Highlight layer data
* @param parsedHightlightLayer defines the Highlight layer data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing the Highlight layer information
* @returns a parsed Highlight layer
*/
HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
var hl = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
var index;
// Excluded meshes
for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
if (mesh) {
hl.addExcludedMesh(mesh);
}
}
// Included meshes
for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
var highlightedMesh = parsedHightlightLayer.meshes[index];
var mesh = scene.getMeshByID(highlightedMesh.meshId);
if (mesh) {
hl.addMesh(mesh, _Maths_math_color__WEBPACK_IMPORTED_MODULE_17__["Color3"].FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
}
}
return hl;
};
/**
* Effect Name of the highlight layer.
*/
HighlightLayer.EffectName = "HighlightLayer";
/**
* The neutral color used during the preparation of the glow effect.
* This is black by default as the blend operation is a blend operation.
*/
HighlightLayer.NeutralColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_17__["Color4"](0, 0, 0, 0);
/**
* Stencil value used for glowing meshes.
*/
HighlightLayer.GlowingMeshStencilReference = 0x02;
/**
* Stencil value used for the other meshes in the scene.
*/
HighlightLayer.NormalMeshStencilReference = 0x01;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], HighlightLayer.prototype, "innerGlow", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], HighlightLayer.prototype, "outerGlow", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], HighlightLayer.prototype, "blurHorizontalSize", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], HighlightLayer.prototype, "blurVerticalSize", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("options")
], HighlightLayer.prototype, "_options", void 0);
return HighlightLayer;
}(_effectLayer__WEBPACK_IMPORTED_MODULE_12__["EffectLayer"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_16__["_TypeStore"].RegisteredTypes["BABYLON.HighlightLayer"] = HighlightLayer;
/***/ }),
/***/ "./Layers/index.ts":
/*!*************************!*\
!*** ./Layers/index.ts ***!
\*************************/
/*! exports provided: EffectLayer, EffectLayerSceneComponent, GlowLayer, HighlightLayer, Layer, LayerSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _effectLayer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./effectLayer */ "./Layers/effectLayer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return _effectLayer__WEBPACK_IMPORTED_MODULE_0__["EffectLayer"]; });
/* harmony import */ var _effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./effectLayerSceneComponent */ "./Layers/effectLayerSceneComponent.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return _effectLayerSceneComponent__WEBPACK_IMPORTED_MODULE_1__["EffectLayerSceneComponent"]; });
/* harmony import */ var _glowLayer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./glowLayer */ "./Layers/glowLayer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return _glowLayer__WEBPACK_IMPORTED_MODULE_2__["GlowLayer"]; });
/* harmony import */ var _highlightLayer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./highlightLayer */ "./Layers/highlightLayer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return _highlightLayer__WEBPACK_IMPORTED_MODULE_3__["HighlightLayer"]; });
/* harmony import */ var _layer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./layer */ "./Layers/layer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return _layer__WEBPACK_IMPORTED_MODULE_4__["Layer"]; });
/* harmony import */ var _layerSceneComponent__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./layerSceneComponent */ "./Layers/layerSceneComponent.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return _layerSceneComponent__WEBPACK_IMPORTED_MODULE_5__["LayerSceneComponent"]; });
/***/ }),
/***/ "./Layers/layer.ts":
/*!*************************!*\
!*** ./Layers/layer.ts ***!
\*************************/
/*! exports provided: Layer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return Layer; });
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _layerSceneComponent__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./layerSceneComponent */ "./Layers/layerSceneComponent.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Shaders_layer_fragment__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Shaders/layer.fragment */ "./Shaders/layer.fragment.ts");
/* harmony import */ var _Shaders_layer_vertex__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Shaders/layer.vertex */ "./Shaders/layer.vertex.ts");
/**
* This represents a full screen 2d layer.
* This can be useful to display a picture in the background of your scene for instance.
* @see https://www.babylonjs-playground.com/#08A2BS#1
*/
var Layer = /** @class */ (function () {
/**
* Instantiates a new layer.
* This represents a full screen 2d layer.
* This can be useful to display a picture in the background of your scene for instance.
* @see https://www.babylonjs-playground.com/#08A2BS#1
* @param name Define the name of the layer in the scene
* @param imgUrl Define the url of the texture to display in the layer
* @param scene Define the scene the layer belongs to
* @param isBackground Defines whether the layer is displayed in front or behind the scene
* @param color Defines a color for the layer
*/
function Layer(
/**
* Define the name of the layer.
*/
name, imgUrl, scene, isBackground, color) {
this.name = name;
/**
* Define the scale of the layer in order to zoom in out of the texture.
*/
this.scale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1, 1);
/**
* Define an offset for the layer in order to shift the texture.
*/
this.offset = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 0);
/**
* Define the alpha blending mode used in the layer in case the texture or color has an alpha.
*/
this.alphaBlendingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].ALPHA_COMBINE;
/**
* Define a mask to restrict the layer to only some of the scene cameras.
*/
this.layerMask = 0x0FFFFFFF;
/**
* Define the list of render target the layer is visible into.
*/
this.renderTargetTextures = [];
/**
* Define if the layer is only used in renderTarget or if it also
* renders in the main frame buffer of the canvas.
*/
this.renderOnlyInRenderTargetTextures = false;
this._vertexBuffers = {};
/**
* An event triggered when the layer is disposed.
*/
this.onDisposeObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered before rendering the scene
*/
this.onBeforeRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
/**
* An event triggered after rendering the scene
*/
this.onAfterRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_0__["Observable"]();
this.texture = imgUrl ? new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"](imgUrl, scene, true) : null;
this.isBackground = isBackground === undefined ? true : isBackground;
this.color = color === undefined ? new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color4"](1, 1, 1, 1) : color;
this._scene = (scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedScene);
var layerComponent = this._scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_7__["SceneComponentConstants"].NAME_LAYER);
if (!layerComponent) {
layerComponent = new _layerSceneComponent__WEBPACK_IMPORTED_MODULE_8__["LayerSceneComponent"](this._scene);
this._scene._addComponent(layerComponent);
}
this._scene.layers.push(this);
var engine = this._scene.getEngine();
// VBO
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
var vertexBuffer = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"](engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind, false, false, 2);
this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = vertexBuffer;
this._createIndexBuffer();
}
Object.defineProperty(Layer.prototype, "onDispose", {
/**
* Back compatibility with callback before the onDisposeObservable existed.
* The set callback will be triggered when the layer has been disposed.
*/
set: function (callback) {
if (this._onDisposeObserver) {
this.onDisposeObservable.remove(this._onDisposeObserver);
}
this._onDisposeObserver = this.onDisposeObservable.add(callback);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Layer.prototype, "onBeforeRender", {
/**
* Back compatibility with callback before the onBeforeRenderObservable existed.
* The set callback will be triggered just before rendering the layer.
*/
set: function (callback) {
if (this._onBeforeRenderObserver) {
this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
}
this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Layer.prototype, "onAfterRender", {
/**
* Back compatibility with callback before the onAfterRenderObservable existed.
* The set callback will be triggered just after rendering the layer.
*/
set: function (callback) {
if (this._onAfterRenderObserver) {
this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
}
this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
},
enumerable: false,
configurable: true
});
Layer.prototype._createIndexBuffer = function () {
var engine = this._scene.getEngine();
// Indices
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = engine.createIndexBuffer(indices);
};
/** @hidden */
Layer.prototype._rebuild = function () {
var vb = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind];
if (vb) {
vb._rebuild();
}
this._createIndexBuffer();
};
/**
* Renders the layer in the scene.
*/
Layer.prototype.render = function () {
var engine = this._scene.getEngine();
var defines = "";
if (this.alphaTest) {
defines = "#define ALPHATEST";
}
if (this.texture && !this.texture.gammaSpace) {
defines += "\r\n#define LINEAR";
}
if (this._previousDefines !== defines) {
this._previousDefines = defines;
this._effect = engine.createEffect("layer", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], defines);
}
var currentEffect = this._effect;
// Check
if (!currentEffect || !currentEffect.isReady() || !this.texture || !this.texture.isReady()) {
return;
}
var engine = this._scene.getEngine();
this.onBeforeRenderObservable.notifyObservers(this);
// Render
engine.enableEffect(currentEffect);
engine.setState(false);
// Texture
currentEffect.setTexture("textureSampler", this.texture);
currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
// Color
currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
// Scale / offset
currentEffect.setVector2("offset", this.offset);
currentEffect.setVector2("scale", this.scale);
// VBOs
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
// Draw order
if (!this.alphaTest) {
engine.setAlphaMode(this.alphaBlendingMode);
engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_5__["Material"].TriangleFillMode, 0, 6);
engine.setAlphaMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_9__["Constants"].ALPHA_DISABLE);
}
else {
engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_5__["Material"].TriangleFillMode, 0, 6);
}
this.onAfterRenderObservable.notifyObservers(this);
};
/**
* Disposes and releases the associated ressources.
*/
Layer.prototype.dispose = function () {
var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
if (this.texture) {
this.texture.dispose();
this.texture = null;
}
// Clean RTT list
this.renderTargetTextures = [];
// Remove from scene
var index = this._scene.layers.indexOf(this);
this._scene.layers.splice(index, 1);
// Callback
this.onDisposeObservable.notifyObservers(this);
this.onDisposeObservable.clear();
this.onAfterRenderObservable.clear();
this.onBeforeRenderObservable.clear();
};
return Layer;
}());
/***/ }),
/***/ "./Layers/layerSceneComponent.ts":
/*!***************************************!*\
!*** ./Layers/layerSceneComponent.ts ***!
\***************************************/
/*! exports provided: LayerSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return LayerSceneComponent; });
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts");
/**
* Defines the layer scene component responsible to manage any layers
* in a given scene.
*/
var LayerSceneComponent = /** @class */ (function () {
/**
* Creates a new instance of the component for the given scene
* @param scene Defines the scene to register the component in
*/
function LayerSceneComponent(scene) {
/**
* The component name helpfull to identify the component in the list of scene components.
*/
this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].NAME_LAYER;
this.scene = scene;
this._engine = scene.getEngine();
scene.layers = new Array();
}
/**
* Registers the component in a given scene
*/
LayerSceneComponent.prototype.register = function () {
this.scene._beforeCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_BEFORECAMERADRAW_LAYER, this, this._drawCameraBackground);
this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_LAYER, this, this._drawCameraForeground);
this.scene._beforeRenderTargetDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_BEFORERENDERTARGETDRAW_LAYER, this, this._drawRenderTargetBackground);
this.scene._afterRenderTargetDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"].STEP_AFTERRENDERTARGETDRAW_LAYER, this, this._drawRenderTargetForeground);
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
LayerSceneComponent.prototype.rebuild = function () {
var layers = this.scene.layers;
for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
var layer = layers_1[_i];
layer._rebuild();
}
};
/**
* Disposes the component and the associated ressources.
*/
LayerSceneComponent.prototype.dispose = function () {
var layers = this.scene.layers;
while (layers.length) {
layers[0].dispose();
}
};
LayerSceneComponent.prototype._draw = function (predicate) {
var layers = this.scene.layers;
if (layers.length) {
this._engine.setDepthBuffer(false);
for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
var layer = layers_2[_i];
if (predicate(layer)) {
layer.render();
}
}
this._engine.setDepthBuffer(true);
}
};
LayerSceneComponent.prototype._drawCameraPredicate = function (layer, isBackground, cameraLayerMask) {
return !layer.renderOnlyInRenderTargetTextures &&
layer.isBackground === isBackground &&
((layer.layerMask & cameraLayerMask) !== 0);
};
LayerSceneComponent.prototype._drawCameraBackground = function (camera) {
var _this = this;
this._draw(function (layer) {
return _this._drawCameraPredicate(layer, true, camera.layerMask);
});
};
LayerSceneComponent.prototype._drawCameraForeground = function (camera) {
var _this = this;
this._draw(function (layer) {
return _this._drawCameraPredicate(layer, false, camera.layerMask);
});
};
LayerSceneComponent.prototype._drawRenderTargetPredicate = function (layer, isBackground, cameraLayerMask, renderTargetTexture) {
return (layer.renderTargetTextures.length > 0) &&
layer.isBackground === isBackground &&
(layer.renderTargetTextures.indexOf(renderTargetTexture) > -1) &&
((layer.layerMask & cameraLayerMask) !== 0);
};
LayerSceneComponent.prototype._drawRenderTargetBackground = function (renderTarget) {
var _this = this;
this._draw(function (layer) {
return _this._drawRenderTargetPredicate(layer, true, _this.scene.activeCamera.layerMask, renderTarget);
});
};
LayerSceneComponent.prototype._drawRenderTargetForeground = function (renderTarget) {
var _this = this;
this._draw(function (layer) {
return _this._drawRenderTargetPredicate(layer, false, _this.scene.activeCamera.layerMask, renderTarget);
});
};
/**
* Adds all the elements from the container to the scene
* @param container the container holding the elements
*/
LayerSceneComponent.prototype.addFromContainer = function (container) {
var _this = this;
if (!container.layers) {
return;
}
container.layers.forEach(function (layer) {
_this.scene.layers.push(layer);
});
};
/**
* Removes all the elements in the container from the scene
* @param container contains the elements to remove
* @param dispose if the removed element should be disposed (default: false)
*/
LayerSceneComponent.prototype.removeFromContainer = function (container, dispose) {
var _this = this;
if (dispose === void 0) { dispose = false; }
if (!container.layers) {
return;
}
container.layers.forEach(function (layer) {
var index = _this.scene.layers.indexOf(layer);
if (index !== -1) {
_this.scene.layers.splice(index, 1);
}
if (dispose) {
layer.dispose();
}
});
};
return LayerSceneComponent;
}());
/***/ }),
/***/ "./Legacy/legacy.ts":
/*!**************************!*\
!*** ./Legacy/legacy.ts ***!
\**************************/
/*! exports provided: AbstractScene, AbstractActionManager, Action, ActionEvent, ActionManager, Condition, ValueCondition, PredicateCondition, StateCondition, SwitchBooleanAction, SetStateAction, SetValueAction, IncrementValueAction, PlayAnimationAction, StopAnimationAction, DoNothingAction, CombineAction, ExecuteCodeAction, SetParentAction, PlaySoundAction, StopSoundAction, InterpolateValueAction, Animatable, _IAnimationState, Animation, TargetedAnimation, AnimationGroup, AnimationPropertiesOverride, EasingFunction, CircleEase, BackEase, BounceEase, CubicEase, ElasticEase, ExponentialEase, PowerEase, QuadraticEase, QuarticEase, QuinticEase, SineEase, BezierCurveEase, RuntimeAnimation, AnimationEvent, AnimationKeyInterpolation, AnimationRange, KeepAssets, InstantiatedEntries, AssetContainer, Analyser, AudioEngine, AudioSceneComponent, Sound, SoundTrack, WeightedSound, AutoRotationBehavior, BouncingBehavior, FramingBehavior, AttachToBoxBehavior, FadeInOutBehavior, MultiPointerScaleBehavior, PointerDragBehavior, SixDofDragBehavior, Bone, BoneIKController, BoneLookController, Skeleton, ArcRotateCameraGamepadInput, ArcRotateCameraKeyboardMoveInput, ArcRotateCameraMouseWheelInput, ArcRotateCameraPointersInput, ArcRotateCameraVRDeviceOrientationInput, FlyCameraKeyboardInput, FlyCameraMouseInput, FollowCameraKeyboardMoveInput, FollowCameraMouseWheelInput, FollowCameraPointersInput, FreeCameraDeviceOrientationInput, FreeCameraGamepadInput, FreeCameraKeyboardMoveInput, FreeCameraMouseInput, FreeCameraTouchInput, FreeCameraVirtualJoystickInput, CameraInputTypes, CameraInputsManager, Camera, TargetCamera, FreeCamera, FreeCameraInputsManager, TouchCamera, ArcRotateCamera, ArcRotateCameraInputsManager, DeviceOrientationCamera, FlyCamera, FlyCameraInputsManager, FollowCamera, ArcFollowCamera, FollowCameraInputsManager, GamepadCamera, AnaglyphArcRotateCamera, AnaglyphFreeCamera, AnaglyphGamepadCamera, AnaglyphUniversalCamera, StereoscopicArcRotateCamera, StereoscopicFreeCamera, StereoscopicGamepadCamera, StereoscopicUniversalCamera, UniversalCamera, VirtualJoysticksCamera, VRCameraMetrics, VRDeviceOrientationArcRotateCamera, VRDeviceOrientationFreeCamera, VRDeviceOrientationGamepadCamera, OnAfterEnteringVRObservableEvent, VRExperienceHelper, WebVRFreeCamera, Collider, DefaultCollisionCoordinator, PickingInfo, IntersectionInfo, _MeshCollisionData, BoundingBox, BoundingInfo, BoundingSphere, Octree, OctreeBlock, OctreeSceneComponent, Ray, AxesViewer, BoneAxesViewer, DebugLayerTab, DebugLayer, PhysicsViewer, RayHelper, SkeletonViewer, DeviceInputSystem, DeviceType, PointerInput, DualShockInput, XboxInput, SwitchInput, DeviceSource, DeviceSourceManager, Constants, ThinEngine, Engine, EngineStore, NullEngineOptions, NullEngine, _OcclusionDataStorage, _forceTransformFeedbackToBundle, EngineView, WebGLPipelineContext, WebGL2ShaderProcessor, NativeEngine, ShaderCodeInliner, PerformanceConfigurator, KeyboardEventTypes, KeyboardInfo, KeyboardInfoPre, PointerEventTypes, PointerInfoBase, PointerInfoPre, PointerInfo, ClipboardEventTypes, ClipboardInfo, DaydreamController, GearVRController, GenericController, OculusTouchController, PoseEnabledControllerType, PoseEnabledControllerHelper, PoseEnabledController, ViveController, WebVRController, WindowsMotionController, XRWindowsMotionController, StickValues, Gamepad, GenericPad, GamepadManager, GamepadSystemSceneComponent, Xbox360Button, Xbox360Dpad, Xbox360Pad, DualShockButton, DualShockDpad, DualShockPad, AxisDragGizmo, AxisScaleGizmo, BoundingBoxGizmo, Gizmo, GizmoManager, PlaneRotationGizmo, PositionGizmo, RotationGizmo, ScaleGizmo, LightGizmo, CameraGizmo, PlaneDragGizmo, EnvironmentHelper, PhotoDome, _forceSceneHelpersToBundle, VideoDome, EngineInstrumentation, SceneInstrumentation, _TimeToken, EffectLayer, EffectLayerSceneComponent, GlowLayer, HighlightLayer, Layer, LayerSceneComponent, LensFlare, LensFlareSystem, LensFlareSystemSceneComponent, Light, ShadowLight, ShadowGenerator, CascadedShadowGenerator, ShadowGeneratorSceneComponent, DirectionalLight, HemisphericLight, PointLight, SpotLight, DefaultLoadingScreen, _BabylonLoaderRegistered, BabylonFileLoaderConfiguration, SceneLoaderAnimationGroupLoadingMode, SceneLoader, SceneLoaderFlags, BackgroundMaterial, ColorCurves, EffectFallbacks, Effect, FresnelParameters, ImageProcessingConfigurationDefines, ImageProcessingConfiguration, Material, MaterialDefines, ThinMaterialHelper, MaterialHelper, MultiMaterial, PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial, PushMaterial, ShaderMaterial, StandardMaterialDefines, StandardMaterial, BaseTexture, ColorGradingTexture, CubeTexture, DynamicTexture, EquiRectangularCubeTexture, HDRFiltering, HDRCubeTexture, HtmlElementTexture, InternalTextureSource, InternalTexture, _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, _BasisTextureLoader, MirrorTexture, MultiRenderTarget, TexturePacker, TexturePackerFrame, CustomProceduralTexture, NoiseProceduralTexture, ProceduralTexture, ProceduralTextureSceneComponent, RawCubeTexture, RawTexture, RawTexture2DArray, RawTexture3D, RefractionTexture, RenderTargetTexture, Texture, VideoTexture, UniformBuffer, MaterialFlags, NodeMaterialBlockTargets, NodeMaterialBlockConnectionPointTypes, NodeMaterialBlockConnectionPointMode, NodeMaterialSystemValues, NodeMaterialModes, NodeMaterialConnectionPointCompatibilityStates, NodeMaterialConnectionPointDirection, NodeMaterialConnectionPoint, NodeMaterialBlock, NodeMaterialDefines, NodeMaterial, VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, LightInformationBlock, FragmentOutputBlock, ImageProcessingBlock, PerturbNormalBlock, DiscardBlock, FrontFacingBlock, DerivativeBlock, FragCoordBlock, ScreenSizeBlock, FogBlock, LightBlock, TextureBlock, ReflectionTextureBlock, CurrentScreenBlock, InputBlock, AnimatedInputBlockTypes, MultiplyBlock, AddBlock, ScaleBlock, ClampBlock, CrossBlock, DotBlock, TransformBlock, RemapBlock, NormalizeBlock, TrigonometryBlockOperations, TrigonometryBlock, ColorMergerBlock, VectorMergerBlock, ColorSplitterBlock, VectorSplitterBlock, LerpBlock, DivideBlock, SubtractBlock, StepBlock, OneMinusBlock, ViewDirectionBlock, FresnelBlock, MaxBlock, MinBlock, DistanceBlock, LengthBlock, NegateBlock, PowBlock, RandomNumberBlock, ArcTan2Block, SmoothStepBlock, ReciprocalBlock, ReplaceColorBlock, PosterizeBlock, WaveBlockKind, WaveBlock, GradientBlockColorStep, GradientBlock, NLerpBlock, WorleyNoise3DBlock, SimplexPerlin3DBlock, NormalBlendBlock, Rotate2dBlock, ReflectBlock, RefractBlock, DesaturateBlock, PBRMetallicRoughnessBlock, SheenBlock, AmbientOcclusionBlock, ReflectivityBlock, AnisotropyBlock, ReflectionBlock, ClearCoatBlock, RefractionBlock, SubSurfaceBlock, ParticleTextureBlock, ParticleRampGradientBlock, ParticleBlendMultiplyBlock, ModBlock, NodeMaterialOptimizer, PropertyTypeForEdition, editableInPropertyPage, EffectRenderer, EffectWrapper, ShadowDepthWrapper, Scalar, Space, Axis, Color3, Color4, TmpColors, ToGammaSpace, ToLinearSpace, Epsilon, Frustum, Orientation, BezierCurve, Angle, Arc2, Path2, Path3D, Curve3, Plane, Size, Vector2, Vector3, Vector4, Quaternion, Matrix, TmpVectors, PositionNormalVertex, PositionNormalTextureVertex, Viewport, SphericalHarmonics, SphericalPolynomial, AbstractMesh, Buffer, VertexBuffer, DracoCompression, CSG, Geometry, GroundMesh, TrailMesh, InstancedMesh, LinesMesh, InstancedLinesMesh, _CreationDataStorage, _InstancesBatch, Mesh, VertexData, MeshBuilder, SimplificationSettings, SimplificationQueue, SimplificationType, QuadraticErrorSimplification, SimplicationQueueSceneComponent, Polygon, PolygonMeshBuilder, SubMesh, MeshLODLevel, TransformNode, BoxBuilder, TiledBoxBuilder, DiscBuilder, RibbonBuilder, SphereBuilder, HemisphereBuilder, CylinderBuilder, TorusBuilder, TorusKnotBuilder, LinesBuilder, PolygonBuilder, ShapeBuilder, LatheBuilder, PlaneBuilder, TiledPlaneBuilder, GroundBuilder, TubeBuilder, PolyhedronBuilder, IcoSphereBuilder, DecalBuilder, DataBuffer, WebGLDataBuffer, MorphTarget, MorphTargetManager, RecastJSPlugin, RecastJSCrowd, Node, Database, BaseParticleSystem, BoxParticleEmitter, ConeParticleEmitter, CylinderParticleEmitter, CylinderDirectedParticleEmitter, HemisphericParticleEmitter, PointParticleEmitter, SphereParticleEmitter, SphereDirectedParticleEmitter, CustomParticleEmitter, MeshParticleEmitter, GPUParticleSystem, Particle, ParticleHelper, ParticleSystem, ParticleSystemSet, SolidParticle, ModelShape, DepthSortedParticle, SolidParticleVertex, SolidParticleSystem, CloudPoint, PointsGroup, PointColor, PointsCloudSystem, SubEmitterType, SubEmitter, PhysicsEngine, PhysicsEngineSceneComponent, PhysicsHelper, PhysicsRadialExplosionEventOptions, PhysicsUpdraftEventOptions, PhysicsVortexEventOptions, PhysicsRadialImpulseFalloff, PhysicsUpdraftMode, PhysicsImpostor, PhysicsJoint, DistanceJoint, MotorEnabledJoint, HingeJoint, Hinge2Joint, CannonJSPlugin, AmmoJSPlugin, OimoJSPlugin, AnaglyphPostProcess, BlackAndWhitePostProcess, BloomEffect, BloomMergePostProcess, BlurPostProcess, ChromaticAberrationPostProcess, CircleOfConfusionPostProcess, ColorCorrectionPostProcess, ConvolutionPostProcess, DepthOfFieldBlurPostProcess, DepthOfFieldEffectBlurLevel, DepthOfFieldEffect, DepthOfFieldMergePostProcessOptions, DepthOfFieldMergePostProcess, DisplayPassPostProcess, ExtractHighlightsPostProcess, FilterPostProcess, FxaaPostProcess, GrainPostProcess, HighlightsPostProcess, ImageProcessingPostProcess, MotionBlurPostProcess, PassPostProcess, PassCubePostProcess, PostProcess, PostProcessManager, RefractionPostProcess, DefaultRenderingPipeline, LensRenderingPipeline, SSAO2RenderingPipeline, SSAORenderingPipeline, StandardRenderingPipeline, PostProcessRenderEffect, PostProcessRenderPipeline, PostProcessRenderPipelineManager, PostProcessRenderPipelineManagerSceneComponent, SharpenPostProcess, StereoscopicInterlacePostProcessI, StereoscopicInterlacePostProcess, TonemappingOperator, TonemapPostProcess, VolumetricLightScatteringPostProcess, VRDistortionCorrectionPostProcess, VRMultiviewToSingleviewPostProcess, ScreenSpaceReflectionPostProcess, ScreenSpaceCurvaturePostProcess, ReflectionProbe, BoundingBoxRenderer, DepthRenderer, DepthRendererSceneComponent, EdgesRenderer, LineEdgesRenderer, GeometryBufferRenderer, GeometryBufferRendererSceneComponent, PrePassRenderer, PrePassRendererSceneComponent, OutlineRenderer, RenderingGroup, RenderingGroupInfo, RenderingManager, UtilityLayerRenderer, Scene, SceneComponentConstants, Stage, Sprite, SpriteManager, SpriteMap, SpritePackedManager, SpriteSceneComponent, AlphaState, DepthCullingState, StencilState, AndOrNotEvaluator, AssetTaskState, AbstractAssetTask, AssetsProgressEvent, ContainerAssetTask, MeshAssetTask, TextFileAssetTask, BinaryFileAssetTask, ImageAssetTask, TextureAssetTask, CubeTextureAssetTask, HDRCubeTextureAssetTask, EquiRectangularCubeTextureAssetTask, AssetsManager, BasisTranscodeConfiguration, BasisTools, DDSTools, expandToProperty, serialize, serializeAsTexture, serializeAsColor3, serializeAsFresnelParameters, serializeAsVector2, serializeAsVector3, serializeAsMeshReference, serializeAsColorCurves, serializeAsColor4, serializeAsImageProcessingConfiguration, serializeAsQuaternion, serializeAsMatrix, serializeAsCameraReference, SerializationHelper, Deferred, EnvironmentTextureTools, MeshExploder, FilesInput, CubeMapToSphericalPolynomialTools, HDRTools, PanoramaToCubeMapTools, KhronosTextureContainer, EventState, Observer, MultiObserver, Observable, PerformanceMonitor, RollingAverage, PromisePolyfill, SceneOptimization, TextureOptimization, HardwareScalingOptimization, ShadowsOptimization, PostProcessesOptimization, LensFlaresOptimization, CustomOptimization, ParticlesOptimization, RenderTargetsOptimization, MergeMeshesOptimization, SceneOptimizerOptions, SceneOptimizer, SceneSerializer, SmartArray, SmartArrayNoDuplicate, StringDictionary, Tags, TextureTools, TGATools, Tools, className, AsyncLoop, VideoRecorder, JoystickAxis, VirtualJoystick, WorkerPool, Logger, _TypeStore, FilesInputStore, DeepCopier, PivotTools, PrecisionDate, ScreenshotTools, WebRequest, InspectableType, BRDFTextureTools, RGBDTextureTools, ColorGradient, Color3Gradient, FactorGradient, GradientHelper, PerfCounter, RetryStrategy, CanvasGenerator, LoadFileError, RequestFileError, ReadFileError, FileTools, StringTools, DataReader, MinMaxReducer, DepthReducer, DataStorage, SceneRecorder, WebXRCamera, WebXREnterExitUIButton, WebXREnterExitUIOptions, WebXREnterExitUI, WebXRExperienceHelper, WebXRInput, WebXRInputSource, WebXRManagedOutputCanvasOptions, WebXRManagedOutputCanvas, WebXRState, WebXRSessionManager, WebXRDefaultExperienceOptions, WebXRDefaultExperience, WebXRFeatureName, WebXRFeaturesManager, WebXRHitTestLegacy, WebXRAnchorSystem, WebXRPlaneDetector, WebXRBackgroundRemover, WebXRMotionControllerTeleportation, WebXRControllerPointerSelection, IWebXRControllerPhysicsOptions, WebXRControllerPhysics, WebXRHitTest, WebXRFeaturePointSystem, WebXRHand, WebXRHandTracking, WebXRAbstractMotionController, WebXRControllerComponent, WebXRGenericTriggerMotionController, WebXRMicrosoftMixedRealityController, WebXRMotionControllerManager, WebXROculusTouchMotionController, WebXRHTCViveMotionController, WebXRProfiledMotionController, Debug */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(global) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Debug", function() { return Debug; });
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index */ "./index.ts");
/* harmony import */ var _Debug_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Debug/index */ "./Debug/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractScene", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractScene"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractActionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractActionManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Action", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Action"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ActionEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ActionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ActionManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Condition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Condition"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ValueCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ValueCondition"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PredicateCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PredicateCondition"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StateCondition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StateCondition"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchBooleanAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SwitchBooleanAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetStateAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetStateAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetValueAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IncrementValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IncrementValueAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlayAnimationAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlayAnimationAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopAnimationAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StopAnimationAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DoNothingAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DoNothingAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CombineAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CombineAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExecuteCodeAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExecuteCodeAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SetParentAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SetParentAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaySoundAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaySoundAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StopSoundAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StopSoundAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InterpolateValueAction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InterpolateValueAction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animatable", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Animatable"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_IAnimationState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_IAnimationState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Animation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Animation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetedAnimation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TargetedAnimation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationPropertiesOverride", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationPropertiesOverride"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EasingFunction", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EasingFunction"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CircleEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BackEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BounceEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BounceEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubicEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubicEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ElasticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ElasticEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExponentialEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExponentialEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowerEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PowerEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuadraticEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuarticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuarticEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuinticEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuinticEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SineEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SineEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurveEase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BezierCurveEase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RuntimeAnimation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RuntimeAnimation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationKeyInterpolation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationKeyInterpolation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimationRange", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimationRange"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeepAssets", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeepAssets"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstantiatedEntries", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstantiatedEntries"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetContainer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetContainer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Analyser", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Analyser"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AudioEngine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AudioSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AudioSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sound", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Sound"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SoundTrack", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SoundTrack"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WeightedSound", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WeightedSound"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AutoRotationBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AutoRotationBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BouncingBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BouncingBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FramingBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FramingBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AttachToBoxBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AttachToBoxBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FadeInOutBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FadeInOutBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiPointerScaleBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiPointerScaleBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerDragBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerDragBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SixDofDragBehavior", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SixDofDragBehavior"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bone", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Bone"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneIKController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneIKController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneLookController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneLookController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Skeleton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Skeleton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraGamepadInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraGamepadInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraKeyboardMoveInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraMouseWheelInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraMouseWheelInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraPointersInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraPointersInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraVRDeviceOrientationInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraVRDeviceOrientationInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraKeyboardInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraKeyboardInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraMouseInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraMouseInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraKeyboardMoveInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraMouseWheelInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraMouseWheelInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraPointersInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraPointersInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraDeviceOrientationInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraDeviceOrientationInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraGamepadInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraGamepadInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraKeyboardMoveInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraKeyboardMoveInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraMouseInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraMouseInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraTouchInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraTouchInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraVirtualJoystickInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraVirtualJoystickInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraInputTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraInputsManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Camera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Camera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TargetCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TargetCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FreeCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FreeCameraInputsManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TouchCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TouchCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcRotateCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcRotateCameraInputsManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceOrientationCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceOrientationCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FlyCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FlyCameraInputsManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcFollowCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcFollowCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FollowCameraInputsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FollowCameraInputsManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphGamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphUniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphUniversalCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicGamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicUniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicUniversalCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniversalCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UniversalCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoysticksCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualJoysticksCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRCameraMetrics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRCameraMetrics"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationArcRotateCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationArcRotateCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDeviceOrientationGamepadCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDeviceOrientationGamepadCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OnAfterEnteringVRObservableEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OnAfterEnteringVRObservableEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRExperienceHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRExperienceHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRFreeCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebVRFreeCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Collider", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Collider"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultCollisionCoordinator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultCollisionCoordinator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PickingInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PickingInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IntersectionInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IntersectionInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_MeshCollisionData", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_MeshCollisionData"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBox", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBox"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingSphere", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingSphere"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Octree", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Octree"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OctreeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OctreeSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OctreeSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Ray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Ray"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxesViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxesViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoneAxesViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoneAxesViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayerTab", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DebugLayerTab"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DebugLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DebugLayer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RayHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RayHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SkeletonViewer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SkeletonViewer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceInputSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceInputSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DualShockInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "XboxInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["XboxInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SwitchInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SwitchInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceSource", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceSource"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeviceSourceManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeviceSourceManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Constants", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Constants"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThinEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ThinEngine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Engine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Engine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineStore"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngineOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NullEngineOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NullEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NullEngine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_OcclusionDataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_OcclusionDataStorage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceTransformFeedbackToBundle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_forceTransformFeedbackToBundle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineView", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineView"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLPipelineContext", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebGLPipelineContext"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGL2ShaderProcessor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebGL2ShaderProcessor"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NativeEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NativeEngine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderCodeInliner", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShaderCodeInliner"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerformanceConfigurator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerformanceConfigurator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardEventTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KeyboardInfoPre", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KeyboardInfoPre"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerEventTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoBase", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfoBase"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfoPre", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfoPre"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointerInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointerInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardEventTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClipboardEventTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClipboardInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClipboardInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DaydreamController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DaydreamController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GearVRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GearVRController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GenericController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OculusTouchController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OculusTouchController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledControllerHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledControllerHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PoseEnabledController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PoseEnabledController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViveController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ViveController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebVRController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebVRController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WindowsMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WindowsMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "XRWindowsMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["XRWindowsMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StickValues", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StickValues"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gamepad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Gamepad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GenericPad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GenericPad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GamepadSystemSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GamepadSystemSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Button", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Button"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Dpad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Dpad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Xbox360Pad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Xbox360Pad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockButton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DualShockButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockDpad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DualShockDpad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DualShockPad", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DualShockPad"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisDragGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxisDragGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AxisScaleGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AxisScaleGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBoxGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Gizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Gizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GizmoManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GizmoManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneRotationGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneRotationGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RotationGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RotationGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScaleGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LightGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CameraGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CameraGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneDragGizmo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneDragGizmo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EnvironmentHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhotoDome", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhotoDome"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_forceSceneHelpersToBundle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_forceSceneHelpersToBundle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoDome", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoDome"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EngineInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EngineInstrumentation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneInstrumentation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneInstrumentation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TimeToken", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TimeToken"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectLayer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectLayerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectLayerSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GlowLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GlowLayer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightLayer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HighlightLayer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Layer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Layer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LayerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LayerSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlare"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlareSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlareSystemSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Light"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowLight"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CascadedShadowGenerator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CascadedShadowGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowGeneratorSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DirectionalLight"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphericLight"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointLight"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpotLight"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultLoadingScreen"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_BabylonLoaderRegistered"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BabylonFileLoaderConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BabylonFileLoaderConfiguration"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderAnimationGroupLoadingMode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderAnimationGroupLoadingMode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneLoaderFlags"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCurves", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorCurves"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectFallbacks", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectFallbacks"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Effect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Effect"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelParameters", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FresnelParameters"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfigurationDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingConfigurationDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingConfiguration"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Material", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Material"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ThinMaterialHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ThinMaterialHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRBaseMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRBaseSimpleMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMetallicRoughnessMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRSpecularGlossinessMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PushMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PushMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShaderMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShaderMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradingTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorGradingTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DynamicTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DynamicTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EquiRectangularCubeTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRFiltering", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRFiltering"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRCubeTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HtmlElementTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HtmlElementTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTextureSource", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InternalTextureSource"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InternalTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InternalTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_DDSTextureLoader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_ENVTextureLoader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_KTXTextureLoader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TGATextureLoader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BasisTextureLoader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_BasisTextureLoader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MirrorTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MirrorTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiRenderTarget", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiRenderTarget"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TexturePacker", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TexturePacker"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TexturePackerFrame", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TexturePackerFrame"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomProceduralTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NoiseProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NoiseProceduralTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ProceduralTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ProceduralTextureSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ProceduralTextureSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawCubeTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawCubeTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture2DArray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture2DArray"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RawTexture3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RawTexture3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderTargetTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Texture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Texture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UniformBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UniformBuffer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaterialFlags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaterialFlags"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockTargets"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointMode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointMode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialSystemValues", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialSystemValues"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialModes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialModes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointCompatibilityStates", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialConnectionPointCompatibilityStates"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointDirection", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialConnectionPointDirection"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialConnectionPoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexOutputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BonesBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancesBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetsBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightInformationBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LightInformationBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FragmentOutputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerturbNormalBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerturbNormalBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscardBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DiscardBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FrontFacingBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FrontFacingBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DerivativeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DerivativeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragCoordBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FragCoordBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenSizeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScreenSizeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FogBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LightBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionTextureBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectionTextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CurrentScreenBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CurrentScreenBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimatedInputBlockTypes", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnimatedInputBlockTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiplyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AddBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScaleBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClampBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CrossBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CrossBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DotBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DotBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TransformBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RemapBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RemapBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NormalizeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NormalizeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlockOperations", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TrigonometryBlockOperations"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TrigonometryBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorMergerBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorMergerBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VectorMergerBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VectorMergerBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorSplitterBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorSplitterBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VectorSplitterBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VectorSplitterBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LerpBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LerpBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DivideBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DivideBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubtractBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubtractBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StepBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StepBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OneMinusBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OneMinusBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViewDirectionBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ViewDirectionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FresnelBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaxBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MaxBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MinBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MinBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DistanceBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DistanceBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LengthBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LengthBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NegateBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NegateBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PowBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RandomNumberBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RandomNumberBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcTan2Block", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ArcTan2Block"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmoothStepBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmoothStepBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReciprocalBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReciprocalBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReplaceColorBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReplaceColorBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PosterizeBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PosterizeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WaveBlockKind", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WaveBlockKind"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WaveBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WaveBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientBlockColorStep", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GradientBlockColorStep"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GradientBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NLerpBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NLerpBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WorleyNoise3DBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WorleyNoise3DBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplexPerlin3DBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplexPerlin3DBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NormalBlendBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NormalBlendBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rotate2dBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Rotate2dBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DesaturateBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DesaturateBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PBRMetallicRoughnessBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SheenBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SheenBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmbientOcclusionBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AmbientOcclusionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectivityBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectivityBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnisotropyBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnisotropyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClearCoatBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ClearCoatBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubSurfaceBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubSurfaceBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleTextureBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleTextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleRampGradientBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleRampGradientBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleBlendMultiplyBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleBlendMultiplyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModBlock", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ModBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialOptimizer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PropertyTypeForEdition", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PropertyTypeForEdition"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "editableInPropertyPage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["editableInPropertyPage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EffectWrapper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EffectWrapper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowDepthWrapper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowDepthWrapper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scalar", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Scalar"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Space", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Space"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Axis", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Axis"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color3"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color4"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TmpColors", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TmpColors"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToGammaSpace", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ToGammaSpace"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ToLinearSpace", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ToLinearSpace"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Epsilon", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Epsilon"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Frustum", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Frustum"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Orientation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Orientation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BezierCurve", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BezierCurve"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Angle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Angle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Arc2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Arc2"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Path2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Path2"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Path3D", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Path3D"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Curve3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Curve3"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Plane", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Plane"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Size", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Size"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector2"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector3"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Vector4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Vector4"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Quaternion", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Quaternion"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Matrix", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Matrix"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TmpVectors", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TmpVectors"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionNormalVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionNormalVertex"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PositionNormalTextureVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PositionNormalTextureVertex"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Viewport", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Viewport"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphericalHarmonics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphericalHarmonics"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphericalPolynomial", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Buffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Buffer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DracoCompression", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DracoCompression"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CSG", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CSG"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Geometry", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Geometry"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroundMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GroundMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrailMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TrailMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancedMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancedMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinesMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LinesMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancedLinesMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InstancedLinesMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_CreationDataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_CreationDataStorage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_InstancesBatch", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_InstancesBatch"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Mesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Mesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexData", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VertexData"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationSettings", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationSettings"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationQueue", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationQueue"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplificationType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplificationType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QuadraticErrorSimplification", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["QuadraticErrorSimplification"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplicationQueueSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SimplicationQueueSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Polygon", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Polygon"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolygonMeshBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolygonMeshBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubMesh", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubMesh"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshLODLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshLODLevel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformNode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoxBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TiledBoxBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TiledBoxBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DiscBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RibbonBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RibbonBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphereBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TorusBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TorusBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TorusKnotBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TorusKnotBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LinesBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LinesBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolygonBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolygonBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShapeBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShapeBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LatheBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LatheBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PlaneBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PlaneBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TiledPlaneBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TiledPlaneBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GroundBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GroundBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TubeBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TubeBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PolyhedronBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PolyhedronBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IcoSphereBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IcoSphereBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DecalBuilder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DecalBuilder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DataBuffer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebGLDataBuffer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebGLDataBuffer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTarget", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTarget"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RecastJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RecastJSPlugin"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RecastJSCrowd", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RecastJSCrowd"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Node", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Node"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Database", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Database"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BaseParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BaseParticleSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoxParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoxParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConeParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ConeParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CylinderDirectedParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CylinderDirectedParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HemisphericParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SphereDirectedParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SphereDirectedParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshParticleEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshParticleEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GPUParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GPUParticleSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Particle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Particle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleSystemSet", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticleSystemSet"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModelShape", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ModelShape"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthSortedParticle", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthSortedParticle"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticleVertex", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticleVertex"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SolidParticleSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SolidParticleSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CloudPoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CloudPoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointsGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointsGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointColor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointColor"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointsCloudSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PointsCloudSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubEmitterType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubEmitterType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubEmitter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SubEmitter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsEngine", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsEngine"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsEngineSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsEngineSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsRadialExplosionEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsRadialExplosionEventOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsUpdraftEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsUpdraftEventOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsVortexEventOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsVortexEventOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsRadialImpulseFalloff", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsRadialImpulseFalloff"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsUpdraftMode", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsUpdraftMode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsImpostor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsImpostor"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PhysicsJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PhysicsJoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DistanceJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DistanceJoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MotorEnabledJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MotorEnabledJoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HingeJoint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HingeJoint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Hinge2Joint", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Hinge2Joint"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CannonJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CannonJSPlugin"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmmoJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AmmoJSPlugin"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OimoJSPlugin", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OimoJSPlugin"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnaglyphPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AnaglyphPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlackAndWhitePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BlackAndWhitePostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BloomEffect"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BloomMergePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BloomMergePostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BlurPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChromaticAberrationPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ChromaticAberrationPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CircleOfConfusionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CircleOfConfusionPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorCorrectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorCorrectionPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ConvolutionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ConvolutionPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldBlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldBlurPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldEffectBlurLevel", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldEffectBlurLevel"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldEffect"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldMergePostProcessOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldMergePostProcessOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthOfFieldMergePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthOfFieldMergePostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DisplayPassPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DisplayPassPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ExtractHighlightsPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ExtractHighlightsPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilterPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilterPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FxaaPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FxaaPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GrainPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GrainPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HighlightsPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HighlightsPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageProcessingPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MotionBlurPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MotionBlurPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PassPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PassPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PassCubePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PassCubePostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RefractionPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DefaultRenderingPipeline"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensRenderingPipeline"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SSAO2RenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SSAO2RenderingPipeline"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SSAORenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SSAORenderingPipeline"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StandardRenderingPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StandardRenderingPipeline"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderEffect", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderEffect"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipeline", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipeline"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipelineManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipelineManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessRenderPipelineManagerSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessRenderPipelineManagerSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SharpenPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SharpenPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicInterlacePostProcessI", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicInterlacePostProcessI"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StereoscopicInterlacePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StereoscopicInterlacePostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TonemappingOperator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TonemappingOperator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TonemapPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TonemapPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VolumetricLightScatteringPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VolumetricLightScatteringPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRDistortionCorrectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRDistortionCorrectionPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VRMultiviewToSingleviewPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VRMultiviewToSingleviewPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenSpaceReflectionPostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScreenSpaceReflectionPostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenSpaceCurvaturePostProcess", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScreenSpaceCurvaturePostProcess"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionProbe", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReflectionProbe"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BoundingBoxRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BoundingBoxRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthRendererSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EdgesRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EdgesRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LineEdgesRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LineEdgesRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GeometryBufferRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GeometryBufferRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GeometryBufferRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GeometryBufferRendererSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrePassRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PrePassRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrePassRendererSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PrePassRendererSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OutlineRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["OutlineRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingGroup", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingGroup"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingGroupInfo", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingGroupInfo"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderingManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderingManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UtilityLayerRenderer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["UtilityLayerRenderer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Scene", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Scene"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneComponentConstants", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneComponentConstants"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Stage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Stage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Sprite", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Sprite"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteMap", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteMap"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpritePackedManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpritePackedManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpriteSceneComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SpriteSceneComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AlphaState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AlphaState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthCullingState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthCullingState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StencilState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StencilState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AndOrNotEvaluator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AndOrNotEvaluator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetTaskState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetTaskState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AbstractAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AbstractAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetsProgressEvent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetsProgressEvent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ContainerAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ContainerAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextFileAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextFileAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BinaryFileAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BinaryFileAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ImageAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeTextureAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRCubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRCubeTextureAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EquiRectangularCubeTextureAssetTask", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EquiRectangularCubeTextureAssetTask"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AssetsManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AssetsManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BasisTranscodeConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BasisTranscodeConfiguration"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BasisTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BasisTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DDSTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DDSTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "expandToProperty", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["expandToProperty"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serialize", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serialize"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsTexture", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsTexture"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColor3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColor3"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsFresnelParameters", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsFresnelParameters"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsVector2", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsVector2"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsVector3", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsVector3"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsMeshReference", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsMeshReference"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColorCurves", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColorCurves"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsColor4", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsColor4"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsImageProcessingConfiguration", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsImageProcessingConfiguration"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsQuaternion", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsQuaternion"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsMatrix", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsMatrix"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "serializeAsCameraReference", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["serializeAsCameraReference"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SerializationHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SerializationHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Deferred", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Deferred"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EnvironmentTextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MeshExploder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MeshExploder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilesInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilesInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CubeMapToSphericalPolynomialTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CubeMapToSphericalPolynomialTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HDRTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HDRTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PanoramaToCubeMapTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PanoramaToCubeMapTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KhronosTextureContainer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "EventState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["EventState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Observer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiObserver", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MultiObserver"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Observable", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Observable"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerformanceMonitor", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerformanceMonitor"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RollingAverage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RollingAverage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PromisePolyfill", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PromisePolyfill"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HardwareScalingOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["HardwareScalingOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowsOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ShadowsOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PostProcessesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PostProcessesOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlaresOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LensFlaresOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CustomOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CustomOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticlesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ParticlesOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RenderTargetsOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RenderTargetsOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MergeMeshesOptimization", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MergeMeshesOptimization"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimizerOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimizerOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneOptimizer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneOptimizer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneSerializer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneSerializer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmartArray", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmartArray"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmartArrayNoDuplicate", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SmartArrayNoDuplicate"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StringDictionary", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StringDictionary"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tags", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tags"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TextureTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TGATools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["TGATools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Tools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Tools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "className", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["className"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AsyncLoop", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["AsyncLoop"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VideoRecorder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VideoRecorder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "JoystickAxis", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["JoystickAxis"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VirtualJoystick", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["VirtualJoystick"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WorkerPool", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WorkerPool"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Logger", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Logger"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TypeStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["_TypeStore"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FilesInputStore", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FilesInputStore"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DeepCopier", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DeepCopier"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PivotTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PivotTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PrecisionDate", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PrecisionDate"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenshotTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ScreenshotTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebRequest", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebRequest"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InspectableType", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["InspectableType"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BRDFTextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["BRDFTextureTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RGBDTextureTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RGBDTextureTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorGradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ColorGradient"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color3Gradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["Color3Gradient"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FactorGradient", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FactorGradient"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["GradientHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerfCounter", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["PerfCounter"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RetryStrategy", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RetryStrategy"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CanvasGenerator", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["CanvasGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LoadFileError", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["LoadFileError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RequestFileError", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["RequestFileError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReadFileError", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["ReadFileError"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FileTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["FileTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StringTools", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["StringTools"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataReader", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DataReader"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MinMaxReducer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["MinMaxReducer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DepthReducer", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DepthReducer"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DataStorage", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["DataStorage"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneRecorder", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["SceneRecorder"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRCamera", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRCamera"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIButton", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUIButton"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUIOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUIOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXREnterExitUI", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXREnterExitUI"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRExperienceHelper", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRExperienceHelper"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInput", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRInput"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRInputSource", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRInputSource"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvasOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRManagedOutputCanvasOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRManagedOutputCanvas", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRManagedOutputCanvas"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRState", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRState"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRSessionManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRSessionManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRDefaultExperienceOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRDefaultExperienceOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRDefaultExperience", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRDefaultExperience"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRFeatureName", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRFeatureName"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRFeaturesManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRFeaturesManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRHitTestLegacy", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRHitTestLegacy"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRAnchorSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRAnchorSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRPlaneDetector", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRPlaneDetector"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRBackgroundRemover", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRBackgroundRemover"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRMotionControllerTeleportation", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRMotionControllerTeleportation"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRControllerPointerSelection", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRControllerPointerSelection"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IWebXRControllerPhysicsOptions", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["IWebXRControllerPhysicsOptions"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRControllerPhysics", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRControllerPhysics"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRHitTest", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRHitTest"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRFeaturePointSystem", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRFeaturePointSystem"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRHand", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRHand"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRHandTracking", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRHandTracking"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRAbstractMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRAbstractMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRControllerComponent", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRControllerComponent"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRGenericTriggerMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRGenericTriggerMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRMicrosoftMixedRealityController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRMicrosoftMixedRealityController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRMotionControllerManager", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRMotionControllerManager"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXROculusTouchMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXROculusTouchMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRHTCViveMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRHTCViveMotionController"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WebXRProfiledMotionController", function() { return _index__WEBPACK_IMPORTED_MODULE_0__["WebXRProfiledMotionController"]; });
/**
* Legacy support, defining window.BABYLON (global variable).
*
* This is the entry point for the UMD module.
* The entry point for a future ESM package should be index.ts
*/
var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
if (typeof globalObject !== "undefined") {
globalObject.BABYLON = BABYLON;
globalObject.BABYLON = globalObject.BABYLON || {};
var BABYLON = globalObject.BABYLON;
BABYLON.Debug = BABYLON.Debug || {};
var keys = [];
for (var key in _Debug_index__WEBPACK_IMPORTED_MODULE_1__) {
BABYLON.Debug[key] = _Debug_index__WEBPACK_IMPORTED_MODULE_1__[key];
keys.push(key);
}
for (var key in _index__WEBPACK_IMPORTED_MODULE_0__) {
BABYLON[key] = _index__WEBPACK_IMPORTED_MODULE_0__[key];
}
}
var Debug = {
AxesViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["AxesViewer"],
BoneAxesViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["BoneAxesViewer"],
PhysicsViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["PhysicsViewer"],
SkeletonViewer: _Debug_index__WEBPACK_IMPORTED_MODULE_1__["SkeletonViewer"],
};
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
/***/ }),
/***/ "./LensFlares/index.ts":
/*!*****************************!*\
!*** ./LensFlares/index.ts ***!
\*****************************/
/*! exports provided: LensFlare, LensFlareSystem, LensFlareSystemSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _lensFlare__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./lensFlare */ "./LensFlares/lensFlare.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return _lensFlare__WEBPACK_IMPORTED_MODULE_0__["LensFlare"]; });
/* harmony import */ var _lensFlareSystem__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lensFlareSystem */ "./LensFlares/lensFlareSystem.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return _lensFlareSystem__WEBPACK_IMPORTED_MODULE_1__["LensFlareSystem"]; });
/* harmony import */ var _lensFlareSystemSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./lensFlareSystemSceneComponent */ "./LensFlares/lensFlareSystemSceneComponent.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return _lensFlareSystemSceneComponent__WEBPACK_IMPORTED_MODULE_2__["LensFlareSystemSceneComponent"]; });
/***/ }),
/***/ "./LensFlares/lensFlare.ts":
/*!*********************************!*\
!*** ./LensFlares/lensFlare.ts ***!
\*********************************/
/*! exports provided: LensFlare */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlare", function() { return LensFlare; });
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/**
* This represents one of the lens effect in a `lensFlareSystem`.
* It controls one of the indiviual texture used in the effect.
* @see https://doc.babylonjs.com/how_to/how_to_use_lens_flares
*/
var LensFlare = /** @class */ (function () {
/**
* Instantiates a new Lens Flare.
* This represents one of the lens effect in a `lensFlareSystem`.
* It controls one of the indiviual texture used in the effect.
* @see https://doc.babylonjs.com/how_to/how_to_use_lens_flares
* @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
* @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
* @param color Define the lens color
* @param imgUrl Define the lens texture url
* @param system Define the `lensFlareSystem` this flare is part of
*/
function LensFlare(
/**
* Define the size of the lens flare in the system (a floating value between 0 and 1)
*/
size,
/**
* Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
*/
position, color, imgUrl, system) {
this.size = size;
this.position = position;
/**
* Define the alpha mode to render this particular lens.
*/
this.alphaMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].ALPHA_ONEONE;
this.color = color || new _Maths_math_color__WEBPACK_IMPORTED_MODULE_0__["Color3"](1, 1, 1);
this.texture = imgUrl ? new _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_1__["Texture"](imgUrl, system.getScene(), true) : null;
this._system = system;
system.lensFlares.push(this);
}
/**
* Creates a new Lens Flare.
* This represents one of the lens effect in a `lensFlareSystem`.
* It controls one of the indiviual texture used in the effect.
* @see https://doc.babylonjs.com/how_to/how_to_use_lens_flares
* @param size Define the size of the lens flare (a floating value between 0 and 1)
* @param position Define the position of the lens flare in the system. (a floating value between -1 and 1). A value of 0 is located on the emitter. A value greater than 0 is beyond the emitter and a value lesser than 0 is behind.
* @param color Define the lens color
* @param imgUrl Define the lens texture url
* @param system Define the `lensFlareSystem` this flare is part of
* @returns The newly created Lens Flare
*/
LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
return new LensFlare(size, position, color, imgUrl, system);
};
/**
* Dispose and release the lens flare with its associated resources.
*/
LensFlare.prototype.dispose = function () {
if (this.texture) {
this.texture.dispose();
}
// Remove from scene
var index = this._system.lensFlares.indexOf(this);
this._system.lensFlares.splice(index, 1);
};
return LensFlare;
}());
/***/ }),
/***/ "./LensFlares/lensFlareSystem.ts":
/*!***************************************!*\
!*** ./LensFlares/lensFlareSystem.ts ***!
\***************************************/
/*! exports provided: LensFlareSystem */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystem", function() { return LensFlareSystem; });
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.scalar */ "./Maths/math.scalar.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Culling_ray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Culling/ray */ "./Culling/ray.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _lensFlare__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./lensFlare */ "./LensFlares/lensFlare.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Shaders_lensFlare_fragment__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../Shaders/lensFlare.fragment */ "./Shaders/lensFlare.fragment.ts");
/* harmony import */ var _Shaders_lensFlare_vertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../Shaders/lensFlare.vertex */ "./Shaders/lensFlare.vertex.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/**
* This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
* It is usually composed of several `lensFlare`.
* @see https://doc.babylonjs.com/how_to/how_to_use_lens_flares
*/
var LensFlareSystem = /** @class */ (function () {
/**
* Instantiates a lens flare system.
* This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
* It is usually composed of several `lensFlare`.
* @see https://doc.babylonjs.com/how_to/how_to_use_lens_flares
* @param name Define the name of the lens flare system in the scene
* @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
* @param scene Define the scene the lens flare system belongs to
*/
function LensFlareSystem(
/**
* Define the name of the lens flare system
*/
name, emitter, scene) {
this.name = name;
/**
* List of lens flares used in this system.
*/
this.lensFlares = new Array();
/**
* Define a limit from the border the lens flare can be visible.
*/
this.borderLimit = 300;
/**
* Define a viewport border we do not want to see the lens flare in.
*/
this.viewportBorder = 0;
/**
* Restricts the rendering of the effect to only the camera rendering this layer mask.
*/
this.layerMask = 0x0FFFFFFF;
this._vertexBuffers = {};
this._isEnabled = true;
this._scene = scene || _Engines_engineStore__WEBPACK_IMPORTED_MODULE_3__["EngineStore"].LastCreatedScene;
LensFlareSystem._SceneComponentInitialization(this._scene);
this._emitter = emitter;
this.id = name;
scene.lensFlareSystems.push(this);
this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
var engine = scene.getEngine();
// VBO
var vertices = [];
vertices.push(1, 1);
vertices.push(-1, 1);
vertices.push(-1, -1);
vertices.push(1, -1);
this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = new _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"](engine, vertices, _Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind, false, false, 2);
// Indices
var indices = [];
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
this._indexBuffer = engine.createIndexBuffer(indices);
// Effects
this._effect = engine.createEffect("lensFlare", [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
}
Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
/**
* Define if the lens flare system is enabled.
*/
get: function () {
return this._isEnabled;
},
set: function (value) {
this._isEnabled = value;
},
enumerable: false,
configurable: true
});
/**
* Get the scene the effects belongs to.
* @returns the scene holding the lens flare system
*/
LensFlareSystem.prototype.getScene = function () {
return this._scene;
};
/**
* Get the emitter of the lens flare system.
* It defines the source of the lens flares (it can be a camera, a light or a mesh).
* @returns the emitter of the lens flare system
*/
LensFlareSystem.prototype.getEmitter = function () {
return this._emitter;
};
/**
* Set the emitter of the lens flare system.
* It defines the source of the lens flares (it can be a camera, a light or a mesh).
* @param newEmitter Define the new emitter of the system
*/
LensFlareSystem.prototype.setEmitter = function (newEmitter) {
this._emitter = newEmitter;
};
/**
* Get the lens flare system emitter position.
* The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
* @returns the position
*/
LensFlareSystem.prototype.getEmitterPosition = function () {
return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
};
/**
* @hidden
*/
LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
var position = this.getEmitterPosition();
position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Project(position, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity(), this._scene.getTransformMatrix(), globalViewport);
this._positionX = position.x;
this._positionY = position.y;
position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
if (this.viewportBorder > 0) {
globalViewport.x -= this.viewportBorder;
globalViewport.y -= this.viewportBorder;
globalViewport.width += this.viewportBorder * 2;
globalViewport.height += this.viewportBorder * 2;
position.x += this.viewportBorder;
position.y += this.viewportBorder;
this._positionX += this.viewportBorder;
this._positionY += this.viewportBorder;
}
if (position.z > 0) {
if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height)) {
return true;
}
}
return true;
}
return false;
};
/** @hidden */
LensFlareSystem.prototype._isVisible = function () {
if (!this._isEnabled || !this._scene.activeCamera) {
return false;
}
var emitterPosition = this.getEmitterPosition();
var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
var distance = direction.length();
direction.normalize();
var ray = new _Culling_ray__WEBPACK_IMPORTED_MODULE_5__["Ray"](this._scene.activeCamera.globalPosition, direction);
var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
};
/**
* @hidden
*/
LensFlareSystem.prototype.render = function () {
if (!this._effect.isReady() || !this._scene.activeCamera) {
return false;
}
var engine = this._scene.getEngine();
var viewport = this._scene.activeCamera.viewport;
var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
// Position
if (!this.computeEffectivePosition(globalViewport)) {
return false;
}
// Visibility
if (!this._isVisible()) {
return false;
}
// Intensity
var awayX;
var awayY;
if (this._positionX < this.borderLimit + globalViewport.x) {
awayX = this.borderLimit + globalViewport.x - this._positionX;
}
else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
}
else {
awayX = 0;
}
if (this._positionY < this.borderLimit + globalViewport.y) {
awayY = this.borderLimit + globalViewport.y - this._positionY;
}
else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
}
else {
awayY = 0;
}
var away = (awayX > awayY) ? awayX : awayY;
away -= this.viewportBorder;
if (away > this.borderLimit) {
away = this.borderLimit;
}
var intensity = 1.0 - _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_2__["Scalar"].Clamp(away / this.borderLimit, 0, 1);
if (intensity < 0) {
return false;
}
if (intensity > 1.0) {
intensity = 1.0;
}
if (this.viewportBorder > 0) {
globalViewport.x += this.viewportBorder;
globalViewport.y += this.viewportBorder;
globalViewport.width -= this.viewportBorder * 2;
globalViewport.height -= this.viewportBorder * 2;
this._positionX -= this.viewportBorder;
this._positionY -= this.viewportBorder;
}
// Position
var centerX = globalViewport.x + globalViewport.width / 2;
var centerY = globalViewport.y + globalViewport.height / 2;
var distX = centerX - this._positionX;
var distY = centerY - this._positionY;
// Effects
engine.enableEffect(this._effect);
engine.setState(false);
engine.setDepthBuffer(false);
// VBOs
engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
// Flares
for (var index = 0; index < this.lensFlares.length; index++) {
var flare = this.lensFlares[index];
if (flare.texture && !flare.texture.isReady()) {
continue;
}
engine.setAlphaMode(flare.alphaMode);
var x = centerX - (distX * flare.position);
var y = centerY - (distY * flare.position);
var cw = flare.size;
var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
var viewportMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
this._effect.setMatrix("viewportMatrix", viewportMatrix);
// Texture
this._effect.setTexture("textureSampler", flare.texture);
// Color
this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
// Draw order
engine.drawElementsType(_Materials_material__WEBPACK_IMPORTED_MODULE_6__["Material"].TriangleFillMode, 0, 6);
}
engine.setDepthBuffer(true);
engine.setAlphaMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_8__["Constants"].ALPHA_DISABLE);
return true;
};
/**
* Dispose and release the lens flare with its associated resources.
*/
LensFlareSystem.prototype.dispose = function () {
var vertexBuffer = this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind];
if (vertexBuffer) {
vertexBuffer.dispose();
this._vertexBuffers[_Meshes_buffer__WEBPACK_IMPORTED_MODULE_4__["VertexBuffer"].PositionKind] = null;
}
if (this._indexBuffer) {
this._scene.getEngine()._releaseBuffer(this._indexBuffer);
this._indexBuffer = null;
}
while (this.lensFlares.length) {
this.lensFlares[0].dispose();
}
// Remove from scene
var index = this._scene.lensFlareSystems.indexOf(this);
this._scene.lensFlareSystems.splice(index, 1);
};
/**
* Parse a lens flare system from a JSON repressentation
* @param parsedLensFlareSystem Define the JSON to parse
* @param scene Define the scene the parsed system should be instantiated in
* @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
* @returns the parsed system
*/
LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
lensFlareSystem.id = parsedLensFlareSystem.id || name;
lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
var parsedFlare = parsedLensFlareSystem.flares[index];
_lensFlare__WEBPACK_IMPORTED_MODULE_7__["LensFlare"].AddFlare(parsedFlare.size, parsedFlare.position, _Maths_math_color__WEBPACK_IMPORTED_MODULE_12__["Color3"].FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
}
return lensFlareSystem;
};
/**
* Serialize the current Lens Flare System into a JSON representation.
* @returns the serialized JSON
*/
LensFlareSystem.prototype.serialize = function () {
var serializationObject = {};
serializationObject.id = this.id;
serializationObject.name = this.name;
serializationObject.emitterId = this.getEmitter().id;
serializationObject.borderLimit = this.borderLimit;
serializationObject.flares = [];
for (var index = 0; index < this.lensFlares.length; index++) {
var flare = this.lensFlares[index];
serializationObject.flares.push({
size: flare.size,
position: flare.position,
color: flare.color.asArray(),
textureName: _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFilename(flare.texture ? flare.texture.name : "")
});
}
return serializationObject;
};
/** @hidden */
LensFlareSystem._SceneComponentInitialization = function (_) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_11__["_DevTools"].WarnImport("LensFlareSystemSceneComponent");
};
return LensFlareSystem;
}());
/***/ }),
/***/ "./LensFlares/lensFlareSystemSceneComponent.ts":
/*!*****************************************************!*\
!*** ./LensFlares/lensFlareSystemSceneComponent.ts ***!
\*****************************************************/
/*! exports provided: LensFlareSystemSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LensFlareSystemSceneComponent", function() { return LensFlareSystemSceneComponent; });
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../abstractScene */ "./abstractScene.ts");
/* harmony import */ var _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./lensFlareSystem */ "./LensFlares/lensFlareSystem.ts");
// Adds the parser to the scene parsers.
_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
// Lens flares
if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
if (!container.lensFlareSystems) {
container.lensFlareSystems = new Array();
}
for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
var lf = _lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__["LensFlareSystem"].Parse(parsedLensFlareSystem, scene, rootUrl);
container.lensFlareSystems.push(lf);
}
}
});
_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.getLensFlareSystemByName = function (name) {
for (var index = 0; index < this.lensFlareSystems.length; index++) {
if (this.lensFlareSystems[index].name === name) {
return this.lensFlareSystems[index];
}
}
return null;
};
_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.getLensFlareSystemByID = function (id) {
for (var index = 0; index < this.lensFlareSystems.length; index++) {
if (this.lensFlareSystems[index].id === id) {
return this.lensFlareSystems[index];
}
}
return null;
};
_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.removeLensFlareSystem = function (toRemove) {
var index = this.lensFlareSystems.indexOf(toRemove);
if (index !== -1) {
this.lensFlareSystems.splice(index, 1);
}
return index;
};
_abstractScene__WEBPACK_IMPORTED_MODULE_2__["AbstractScene"].prototype.addLensFlareSystem = function (newLensFlareSystem) {
this.lensFlareSystems.push(newLensFlareSystem);
};
/**
* Defines the lens flare scene component responsible to manage any lens flares
* in a given scene.
*/
var LensFlareSystemSceneComponent = /** @class */ (function () {
/**
* Creates a new instance of the component for the given scene
* @param scene Defines the scene to register the component in
*/
function LensFlareSystemSceneComponent(scene) {
/**
* The component name helpfull to identify the component in the list of scene components.
*/
this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM;
this.scene = scene;
scene.lensFlareSystems = new Array();
}
/**
* Registers the component in a given scene
*/
LensFlareSystemSceneComponent.prototype.register = function () {
this.scene._afterCameraDrawStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
LensFlareSystemSceneComponent.prototype.rebuild = function () {
// Nothing to do for lens flare
};
/**
* Adds all the elements from the container to the scene
* @param container the container holding the elements
*/
LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
var _this = this;
if (!container.lensFlareSystems) {
return;
}
container.lensFlareSystems.forEach(function (o) {
_this.scene.addLensFlareSystem(o);
});
};
/**
* Removes all the elements in the container from the scene
* @param container contains the elements to remove
* @param dispose if the removed element should be disposed (default: false)
*/
LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container, dispose) {
var _this = this;
if (!container.lensFlareSystems) {
return;
}
container.lensFlareSystems.forEach(function (o) {
_this.scene.removeLensFlareSystem(o);
if (dispose) {
o.dispose();
}
});
};
/**
* Serializes the component data to the specified json object
* @param serializationObject The object to serialize to
*/
LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
// Lens flares
serializationObject.lensFlareSystems = [];
var lensFlareSystems = this.scene.lensFlareSystems;
for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
var lensFlareSystem = lensFlareSystems_1[_i];
serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
}
};
/**
* Disposes the component and the associated ressources.
*/
LensFlareSystemSceneComponent.prototype.dispose = function () {
var lensFlareSystems = this.scene.lensFlareSystems;
while (lensFlareSystems.length) {
lensFlareSystems[0].dispose();
}
};
LensFlareSystemSceneComponent.prototype._draw = function (camera) {
// Lens flares
if (this.scene.lensFlaresEnabled) {
var lensFlareSystems = this.scene.lensFlareSystems;
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
var lensFlareSystem = lensFlareSystems_2[_i];
if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
lensFlareSystem.render();
}
}
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
}
};
return LensFlareSystemSceneComponent;
}());
_lensFlareSystem__WEBPACK_IMPORTED_MODULE_3__["LensFlareSystem"]._SceneComponentInitialization = function (scene) {
var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_1__["SceneComponentConstants"].NAME_LENSFLARESYSTEM);
if (!component) {
component = new LensFlareSystemSceneComponent(scene);
scene._addComponent(component);
}
};
/***/ }),
/***/ "./Lights/Shadows/cascadedShadowGenerator.ts":
/*!***************************************************!*\
!*** ./Lights/Shadows/cascadedShadowGenerator.ts ***!
\***************************************************/
/*! exports provided: CascadedShadowGenerator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CascadedShadowGenerator", function() { return CascadedShadowGenerator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Shaders_shadowMap_fragment__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Shaders/shadowMap.fragment */ "./Shaders/shadowMap.fragment.ts");
/* harmony import */ var _Shaders_shadowMap_vertex__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Shaders/shadowMap.vertex */ "./Shaders/shadowMap.vertex.ts");
/* harmony import */ var _Shaders_depthBoxBlur_fragment__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Shaders/depthBoxBlur.fragment */ "./Shaders/depthBoxBlur.fragment.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts");
/* harmony import */ var _Culling_boundingInfo__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Culling/boundingInfo */ "./Culling/boundingInfo.ts");
/* harmony import */ var _Misc_depthReducer__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Misc/depthReducer */ "./Misc/depthReducer.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Engines/engineStore */ "./Engines/engineStore.ts");
var UpDir = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up();
var ZeroVec = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
var tmpv1 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](), tmpv2 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](), tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](), tmpMatrix2 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"]();
/**
* A CSM implementation allowing casting shadows on large scenes.
* Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows
* Based on: https://github.com/TheRealMJP/Shadows and https://johanmedestrom.wordpress.com/2016/03/18/opengl-cascaded-shadow-maps/
*/
var CascadedShadowGenerator = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CascadedShadowGenerator, _super);
/**
* Creates a Cascaded Shadow Generator object.
* A ShadowGenerator is the required tool to use the shadows.
* Each directional light casting shadows needs to use its own ShadowGenerator.
* Documentation : https://doc.babylonjs.com/babylon101/cascadedShadows
* @param mapSize The size of the texture what stores the shadows. Example : 1024.
* @param light The directional light object generating the shadows.
* @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
*/
function CascadedShadowGenerator(mapSize, light, usefulFloatFirst) {
var _this = _super.call(this, mapSize, light, usefulFloatFirst) || this;
if (!CascadedShadowGenerator.IsSupported) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_11__["Logger"].Error("CascadedShadowMap needs WebGL 2 support.");
return _this;
}
_this.usePercentageCloserFiltering = true;
return _this;
}
CascadedShadowGenerator.prototype._validateFilter = function (filter) {
if (filter === _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_NONE ||
filter === _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_PCF ||
filter === _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_PCSS) {
return filter;
}
console.error('Unsupported filter "' + filter + '"!');
return _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_NONE;
};
Object.defineProperty(CascadedShadowGenerator.prototype, "numCascades", {
/**
* Gets or set the number of cascades used by the CSM.
*/
get: function () {
return this._numCascades;
},
set: function (value) {
value = Math.min(Math.max(value, CascadedShadowGenerator.MIN_CASCADES_COUNT), CascadedShadowGenerator.MAX_CASCADES_COUNT);
if (value === this._numCascades) {
return;
}
this._numCascades = value;
this.recreateShadowMap();
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "freezeShadowCastersBoundingInfo", {
/**
* Enables or disables the shadow casters bounding info computation.
* If your shadow casters don't move, you can disable this feature.
* If it is enabled, the bounding box computation is done every frame.
*/
get: function () {
return this._freezeShadowCastersBoundingInfo;
},
set: function (freeze) {
if (this._freezeShadowCastersBoundingInfoObservable && freeze) {
this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
this._freezeShadowCastersBoundingInfoObservable = null;
}
if (!this._freezeShadowCastersBoundingInfoObservable && !freeze) {
this._freezeShadowCastersBoundingInfoObservable = this._scene.onBeforeRenderObservable.add(this._computeShadowCastersBoundingInfo.bind(this));
}
this._freezeShadowCastersBoundingInfo = freeze;
if (freeze) {
this._computeShadowCastersBoundingInfo();
}
},
enumerable: false,
configurable: true
});
CascadedShadowGenerator.prototype._computeShadowCastersBoundingInfo = function () {
this._scbiMin.copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._scbiMax.copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
if (this._shadowMap && this._shadowMap.renderList) {
var renderList = this._shadowMap.renderList;
for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
var mesh = renderList[meshIndex];
if (!mesh) {
continue;
}
var boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;
this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);
this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);
}
var meshes = this._scene.meshes;
for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
var mesh = meshes[meshIndex];
if (!mesh || !mesh.isVisible || !mesh.isEnabled || !mesh.receiveShadows) {
continue;
}
var boundingInfo = mesh.getBoundingInfo(), boundingBox = boundingInfo.boundingBox;
this._scbiMin.minimizeInPlace(boundingBox.minimumWorld);
this._scbiMax.maximizeInPlace(boundingBox.maximumWorld);
}
}
this._shadowCastersBoundingInfo.reConstruct(this._scbiMin, this._scbiMax);
};
Object.defineProperty(CascadedShadowGenerator.prototype, "shadowCastersBoundingInfo", {
/**
* Gets or sets the shadow casters bounding info.
* If you provide your own shadow casters bounding info, first enable freezeShadowCastersBoundingInfo
* so that the system won't overwrite the bounds you provide
*/
get: function () {
return this._shadowCastersBoundingInfo;
},
set: function (boundingInfo) {
this._shadowCastersBoundingInfo = boundingInfo;
},
enumerable: false,
configurable: true
});
/**
* Sets the minimal and maximal distances to use when computing the cascade breaks.
*
* The values of min / max are typically the depth zmin and zmax values of your scene, for a given frame.
* If you don't know these values, simply leave them to their defaults and don't call this function.
* @param min minimal distance for the breaks (default to 0.)
* @param max maximal distance for the breaks (default to 1.)
*/
CascadedShadowGenerator.prototype.setMinMaxDistance = function (min, max) {
if (this._minDistance === min && this._maxDistance === max) {
return;
}
if (min > max) {
min = 0;
max = 1;
}
if (min < 0) {
min = 0;
}
if (max > 1) {
max = 1;
}
this._minDistance = min;
this._maxDistance = max;
this._breaksAreDirty = true;
};
Object.defineProperty(CascadedShadowGenerator.prototype, "minDistance", {
/** Gets the minimal distance used in the cascade break computation */
get: function () {
return this._minDistance;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "maxDistance", {
/** Gets the maximal distance used in the cascade break computation */
get: function () {
return this._maxDistance;
},
enumerable: false,
configurable: true
});
/**
* Gets the class name of that object
* @returns "CascadedShadowGenerator"
*/
CascadedShadowGenerator.prototype.getClassName = function () {
return CascadedShadowGenerator.CLASSNAME;
};
/**
* Gets a cascade minimum extents
* @param cascadeIndex index of the cascade
* @returns the minimum cascade extents
*/
CascadedShadowGenerator.prototype.getCascadeMinExtents = function (cascadeIndex) {
return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMinExtents[cascadeIndex] : null;
};
/**
* Gets a cascade maximum extents
* @param cascadeIndex index of the cascade
* @returns the maximum cascade extents
*/
CascadedShadowGenerator.prototype.getCascadeMaxExtents = function (cascadeIndex) {
return cascadeIndex >= 0 && cascadeIndex < this._numCascades ? this._cascadeMaxExtents[cascadeIndex] : null;
};
Object.defineProperty(CascadedShadowGenerator.prototype, "shadowMaxZ", {
/**
* Gets the shadow max z distance. It's the limit beyond which shadows are not displayed.
* It defaults to camera.maxZ
*/
get: function () {
if (!this._scene || !this._scene.activeCamera) {
return 0;
}
return this._shadowMaxZ;
},
/**
* Sets the shadow max z distance.
*/
set: function (value) {
if (!this._scene || !this._scene.activeCamera) {
this._shadowMaxZ = value;
return;
}
if (this._shadowMaxZ === value || value < this._scene.activeCamera.minZ || value > this._scene.activeCamera.maxZ) {
return;
}
this._shadowMaxZ = value;
this._light._markMeshesAsLightDirty();
this._breaksAreDirty = true;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "debug", {
/**
* Gets or sets the debug flag.
* When enabled, the cascades are materialized by different colors on the screen.
*/
get: function () {
return this._debug;
},
set: function (dbg) {
this._debug = dbg;
this._light._markMeshesAsLightDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "depthClamp", {
/**
* Gets or sets the depth clamping value.
*
* When enabled, it improves the shadow quality because the near z plane of the light frustum don't need to be adjusted
* to account for the shadow casters far away.
*
* Note that this property is incompatible with PCSS filtering, so it won't be used in that case.
*/
get: function () {
return this._depthClamp;
},
set: function (value) {
this._depthClamp = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "cascadeBlendPercentage", {
/**
* Gets or sets the percentage of blending between two cascades (value between 0. and 1.).
* It defaults to 0.1 (10% blending).
*/
get: function () {
return this._cascadeBlendPercentage;
},
set: function (value) {
this._cascadeBlendPercentage = value;
this._light._markMeshesAsLightDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "lambda", {
/**
* Gets or set the lambda parameter.
* This parameter is used to split the camera frustum and create the cascades.
* It's a value between 0. and 1.: If 0, the split is a uniform split of the frustum, if 1 it is a logarithmic split.
* For all values in-between, it's a linear combination of the uniform and logarithm split algorithm.
*/
get: function () {
return this._lambda;
},
set: function (value) {
var lambda = Math.min(Math.max(value, 0), 1);
if (this._lambda == lambda) {
return;
}
this._lambda = lambda;
this._breaksAreDirty = true;
},
enumerable: false,
configurable: true
});
/**
* Gets the view matrix corresponding to a given cascade
* @param cascadeNum cascade to retrieve the view matrix from
* @returns the cascade view matrix
*/
CascadedShadowGenerator.prototype.getCascadeViewMatrix = function (cascadeNum) {
return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._viewMatrices[cascadeNum] : null;
};
/**
* Gets the projection matrix corresponding to a given cascade
* @param cascadeNum cascade to retrieve the projection matrix from
* @returns the cascade projection matrix
*/
CascadedShadowGenerator.prototype.getCascadeProjectionMatrix = function (cascadeNum) {
return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._projectionMatrices[cascadeNum] : null;
};
/**
* Gets the transformation matrix corresponding to a given cascade
* @param cascadeNum cascade to retrieve the transformation matrix from
* @returns the cascade transformation matrix
*/
CascadedShadowGenerator.prototype.getCascadeTransformMatrix = function (cascadeNum) {
return cascadeNum >= 0 && cascadeNum < this._numCascades ? this._transformMatrices[cascadeNum] : null;
};
/**
* Sets the depth renderer to use when autoCalcDepthBounds is enabled.
*
* Note that if no depth renderer is set, a new one will be automatically created internally when necessary.
*
* You should call this function if you already have a depth renderer enabled in your scene, to avoid
* doing multiple depth rendering each frame. If you provide your own depth renderer, make sure it stores linear depth!
* @param depthRenderer The depth renderer to use when autoCalcDepthBounds is enabled. If you pass null or don't call this function at all, a depth renderer will be automatically created
*/
CascadedShadowGenerator.prototype.setDepthRenderer = function (depthRenderer) {
this._depthRenderer = depthRenderer;
if (this._depthReducer) {
this._depthReducer.setDepthRenderer(this._depthRenderer);
}
};
Object.defineProperty(CascadedShadowGenerator.prototype, "autoCalcDepthBounds", {
/**
* Gets or sets the autoCalcDepthBounds property.
*
* When enabled, a depth rendering pass is first performed (with an internally created depth renderer or with the one
* you provide by calling setDepthRenderer). Then, a min/max reducing is applied on the depth map to compute the
* minimal and maximal depth of the map and those values are used as inputs for the setMinMaxDistance() function.
* It can greatly enhance the shadow quality, at the expense of more GPU works.
* When using this option, you should increase the value of the lambda parameter, and even set it to 1 for best results.
*/
get: function () {
return this._autoCalcDepthBounds;
},
set: function (value) {
var _this = this;
var camera = this._scene.activeCamera;
if (!camera) {
return;
}
this._autoCalcDepthBounds = value;
if (!value) {
if (this._depthReducer) {
this._depthReducer.deactivate();
}
this.setMinMaxDistance(0, 1);
return;
}
if (!this._depthReducer) {
this._depthReducer = new _Misc_depthReducer__WEBPACK_IMPORTED_MODULE_10__["DepthReducer"](camera);
this._depthReducer.onAfterReductionPerformed.add(function (minmax) {
var min = minmax.min, max = minmax.max;
if (min >= max) {
min = 0;
max = 1;
}
if (min != _this._minDistance || max != _this._maxDistance) {
_this.setMinMaxDistance(min, max);
}
});
this._depthReducer.setDepthRenderer(this._depthRenderer);
}
this._depthReducer.activate();
},
enumerable: false,
configurable: true
});
Object.defineProperty(CascadedShadowGenerator.prototype, "autoCalcDepthBoundsRefreshRate", {
/**
* Defines the refresh rate of the min/max computation used when autoCalcDepthBounds is set to true
* Use 0 to compute just once, 1 to compute on every frame, 2 to compute every two frames and so on...
* Note that if you provided your own depth renderer through a call to setDepthRenderer, you are responsible
* for setting the refresh rate on the renderer yourself!
*/
get: function () {
var _a, _b, _c;
return (_c = (_b = (_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) === null || _b === void 0 ? void 0 : _b.getDepthMap().refreshRate) !== null && _c !== void 0 ? _c : -1;
},
set: function (value) {
var _a;
if ((_a = this._depthReducer) === null || _a === void 0 ? void 0 : _a.depthRenderer) {
this._depthReducer.depthRenderer.getDepthMap().refreshRate = value;
}
},
enumerable: false,
configurable: true
});
/**
* Create the cascade breaks according to the lambda, shadowMaxZ and min/max distance properties, as well as the camera near and far planes.
* This function is automatically called when updating lambda, shadowMaxZ and min/max distances, however you should call it yourself if
* you change the camera near/far planes!
*/
CascadedShadowGenerator.prototype.splitFrustum = function () {
this._breaksAreDirty = true;
};
CascadedShadowGenerator.prototype._splitFrustum = function () {
var camera = this._scene.activeCamera;
if (!camera) {
return;
}
var near = camera.minZ, far = camera.maxZ, cameraRange = far - near, minDistance = this._minDistance, maxDistance = this._shadowMaxZ < far && this._shadowMaxZ >= near ? Math.min((this._shadowMaxZ - near) / (far - near), this._maxDistance) : this._maxDistance;
var minZ = near + minDistance * cameraRange, maxZ = near + maxDistance * cameraRange;
var range = maxZ - minZ, ratio = maxZ / minZ;
for (var cascadeIndex = 0; cascadeIndex < this._cascades.length; ++cascadeIndex) {
var p = (cascadeIndex + 1) / this._numCascades, log = minZ * (Math.pow(ratio, p)), uniform = minZ + range * p;
var d = this._lambda * (log - uniform) + uniform;
this._cascades[cascadeIndex].prevBreakDistance = cascadeIndex === 0 ? minDistance : this._cascades[cascadeIndex - 1].breakDistance;
this._cascades[cascadeIndex].breakDistance = (d - near) / cameraRange;
this._viewSpaceFrustumsZ[cascadeIndex] = near + this._cascades[cascadeIndex].breakDistance * cameraRange;
this._frustumLengths[cascadeIndex] = (this._cascades[cascadeIndex].breakDistance - this._cascades[cascadeIndex].prevBreakDistance) * cameraRange;
}
this._breaksAreDirty = false;
};
CascadedShadowGenerator.prototype._computeMatrices = function () {
var scene = this._scene;
var camera = scene.activeCamera;
if (!camera) {
return;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].NormalizeToRef(this._light.getShadowDirection(0), this._lightDirection);
if (Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this._lightDirection, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up())) === 1.0) {
this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
}
this._cachedDirection.copyFrom(this._lightDirection);
for (var cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
this._computeFrustumInWorldSpace(cascadeIndex);
this._computeCascadeFrustum(cascadeIndex);
this._cascadeMaxExtents[cascadeIndex].subtractToRef(this._cascadeMinExtents[cascadeIndex], tmpv1); // tmpv1 = cascadeExtents
// Get position of the shadow camera
this._frustumCenter[cascadeIndex].addToRef(this._lightDirection.scale(this._cascadeMinExtents[cascadeIndex].z), this._shadowCameraPos[cascadeIndex]);
// Come up with a new orthographic camera for the shadow caster
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].LookAtLHToRef(this._shadowCameraPos[cascadeIndex], this._frustumCenter[cascadeIndex], UpDir, this._viewMatrices[cascadeIndex]);
var minZ = 0, maxZ = tmpv1.z;
// Try to tighten minZ and maxZ based on the bounding box of the shadow casters
var boundingInfo = this._shadowCastersBoundingInfo;
boundingInfo.update(this._viewMatrices[cascadeIndex]);
maxZ = Math.min(maxZ, boundingInfo.boundingBox.maximumWorld.z);
if (!this._depthClamp || this.filter === _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_PCSS) {
// If we don't use depth clamping, we must set minZ so that all shadow casters are in the light frustum
minZ = Math.min(minZ, boundingInfo.boundingBox.minimumWorld.z);
}
else {
// If using depth clamping, we can adjust minZ to reduce the [minZ, maxZ] range (and get some additional precision in the shadow map)
minZ = Math.max(minZ, boundingInfo.boundingBox.minimumWorld.z);
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].OrthoOffCenterLHToRef(this._cascadeMinExtents[cascadeIndex].x, this._cascadeMaxExtents[cascadeIndex].x, this._cascadeMinExtents[cascadeIndex].y, this._cascadeMaxExtents[cascadeIndex].y, minZ, maxZ, this._projectionMatrices[cascadeIndex]);
this._cascadeMinExtents[cascadeIndex].z = minZ;
this._cascadeMaxExtents[cascadeIndex].z = maxZ;
this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
// Create the rounding matrix, by projecting the world-space origin and determining
// the fractional offset in texel space
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(ZeroVec, this._transformMatrices[cascadeIndex], tmpv1); // tmpv1 = shadowOrigin
tmpv1.scaleInPlace(this._mapSize / 2);
tmpv2.copyFromFloats(Math.round(tmpv1.x), Math.round(tmpv1.y), Math.round(tmpv1.z)); // tmpv2 = roundedOrigin
tmpv2.subtractInPlace(tmpv1).scaleInPlace(2 / this._mapSize); // tmpv2 = roundOffset
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].TranslationToRef(tmpv2.x, tmpv2.y, 0.0, tmpMatrix);
this._projectionMatrices[cascadeIndex].multiplyToRef(tmpMatrix, this._projectionMatrices[cascadeIndex]);
this._viewMatrices[cascadeIndex].multiplyToRef(this._projectionMatrices[cascadeIndex], this._transformMatrices[cascadeIndex]);
this._transformMatrices[cascadeIndex].copyToArray(this._transformMatricesAsArray, cascadeIndex * 16);
}
};
// Get the 8 points of the view frustum in world space
CascadedShadowGenerator.prototype._computeFrustumInWorldSpace = function (cascadeIndex) {
if (!this._scene.activeCamera) {
return;
}
var prevSplitDist = this._cascades[cascadeIndex].prevBreakDistance, splitDist = this._cascades[cascadeIndex].breakDistance;
this._scene.activeCamera.getViewMatrix(); // make sure the transformation matrix we get when calling 'getTransformationMatrix()' is calculated with an up to date view matrix
var invViewProj = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Invert(this._scene.activeCamera.getTransformationMatrix());
for (var cornerIndex = 0; cornerIndex < CascadedShadowGenerator.frustumCornersNDCSpace.length; ++cornerIndex) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(CascadedShadowGenerator.frustumCornersNDCSpace[cornerIndex], invViewProj, this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
}
// Get the corners of the current cascade slice of the view frustum
for (var cornerIndex = 0; cornerIndex < CascadedShadowGenerator.frustumCornersNDCSpace.length / 2; ++cornerIndex) {
tmpv1.copyFrom(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4]).subtractInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
tmpv2.copyFrom(tmpv1).scaleInPlace(prevSplitDist); // near corner ray
tmpv1.scaleInPlace(splitDist); // far corner ray
tmpv1.addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
this._frustumCornersWorldSpace[cascadeIndex][cornerIndex + 4].copyFrom(tmpv1);
this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].addInPlace(tmpv2);
}
};
CascadedShadowGenerator.prototype._computeCascadeFrustum = function (cascadeIndex) {
this._cascadeMinExtents[cascadeIndex].copyFromFloats(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cascadeMaxExtents[cascadeIndex].copyFromFloats(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);
this._frustumCenter[cascadeIndex].copyFromFloats(0, 0, 0);
var camera = this._scene.activeCamera;
if (!camera) {
return;
}
// Calculate the centroid of the view frustum slice
for (var cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
this._frustumCenter[cascadeIndex].addInPlace(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex]);
}
this._frustumCenter[cascadeIndex].scaleInPlace(1 / this._frustumCornersWorldSpace[cascadeIndex].length);
if (this.stabilizeCascades) {
// Calculate the radius of a bounding sphere surrounding the frustum corners
var sphereRadius = 0;
for (var cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
var dist = this._frustumCornersWorldSpace[cascadeIndex][cornerIndex].subtractToRef(this._frustumCenter[cascadeIndex], tmpv1).length();
sphereRadius = Math.max(sphereRadius, dist);
}
sphereRadius = Math.ceil(sphereRadius * 16) / 16;
this._cascadeMaxExtents[cascadeIndex].copyFromFloats(sphereRadius, sphereRadius, sphereRadius);
this._cascadeMinExtents[cascadeIndex].copyFromFloats(-sphereRadius, -sphereRadius, -sphereRadius);
}
else {
// Create a temporary view matrix for the light
var lightCameraPos = this._frustumCenter[cascadeIndex];
this._frustumCenter[cascadeIndex].addToRef(this._lightDirection, tmpv1); // tmpv1 = look at
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].LookAtLHToRef(lightCameraPos, tmpv1, UpDir, tmpMatrix); // matrix = lightView
// Calculate an AABB around the frustum corners
for (var cornerIndex = 0; cornerIndex < this._frustumCornersWorldSpace[cascadeIndex].length; ++cornerIndex) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].TransformCoordinatesToRef(this._frustumCornersWorldSpace[cascadeIndex][cornerIndex], tmpMatrix, tmpv1);
this._cascadeMinExtents[cascadeIndex].minimizeInPlace(tmpv1);
this._cascadeMaxExtents[cascadeIndex].maximizeInPlace(tmpv1);
}
}
};
Object.defineProperty(CascadedShadowGenerator, "IsSupported", {
/**
* Support test.
*/
get: function () {
var engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_12__["EngineStore"].LastCreatedEngine;
if (!engine) {
return false;
}
return engine.webGLVersion != 1;
},
enumerable: false,
configurable: true
});
CascadedShadowGenerator.prototype._initializeGenerator = function () {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
this.penumbraDarkness = (_a = this.penumbraDarkness) !== null && _a !== void 0 ? _a : 1.0;
this._numCascades = (_b = this._numCascades) !== null && _b !== void 0 ? _b : CascadedShadowGenerator.DEFAULT_CASCADES_COUNT;
this.stabilizeCascades = (_c = this.stabilizeCascades) !== null && _c !== void 0 ? _c : false;
this._freezeShadowCastersBoundingInfoObservable = (_d = this._freezeShadowCastersBoundingInfoObservable) !== null && _d !== void 0 ? _d : null;
this.freezeShadowCastersBoundingInfo = (_e = this.freezeShadowCastersBoundingInfo) !== null && _e !== void 0 ? _e : false;
this._scbiMin = (_f = this._scbiMin) !== null && _f !== void 0 ? _f : new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0);
this._scbiMax = (_g = this._scbiMax) !== null && _g !== void 0 ? _g : new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0);
this._shadowCastersBoundingInfo = (_h = this._shadowCastersBoundingInfo) !== null && _h !== void 0 ? _h : new _Culling_boundingInfo__WEBPACK_IMPORTED_MODULE_9__["BoundingInfo"](new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0), new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](0, 0, 0));
this._breaksAreDirty = (_j = this._breaksAreDirty) !== null && _j !== void 0 ? _j : true;
this._minDistance = (_k = this._minDistance) !== null && _k !== void 0 ? _k : 0;
this._maxDistance = (_l = this._maxDistance) !== null && _l !== void 0 ? _l : 1;
this._currentLayer = (_m = this._currentLayer) !== null && _m !== void 0 ? _m : 0;
this._shadowMaxZ = (_q = (_o = this._shadowMaxZ) !== null && _o !== void 0 ? _o : (_p = this._scene.activeCamera) === null || _p === void 0 ? void 0 : _p.maxZ) !== null && _q !== void 0 ? _q : 10000;
this._debug = (_r = this._debug) !== null && _r !== void 0 ? _r : false;
this._depthClamp = (_s = this._depthClamp) !== null && _s !== void 0 ? _s : true;
this._cascadeBlendPercentage = (_t = this._cascadeBlendPercentage) !== null && _t !== void 0 ? _t : 0.1;
this._lambda = (_u = this._lambda) !== null && _u !== void 0 ? _u : 0.5;
this._autoCalcDepthBounds = (_v = this._autoCalcDepthBounds) !== null && _v !== void 0 ? _v : false;
_super.prototype._initializeGenerator.call(this);
};
CascadedShadowGenerator.prototype._createTargetRenderTexture = function () {
var size = { width: this._mapSize, height: this._mapSize, layers: this.numCascades };
this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_2__["RenderTargetTexture"](this._light.name + "_shadowMap", size, this._scene, false, true, this._textureType, false, undefined, false, false, undefined /*, Constants.TEXTUREFORMAT_RED*/);
this._shadowMap.createDepthStencilTexture(_Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].LESS, true);
};
CascadedShadowGenerator.prototype._initializeShadowMap = function () {
var _this = this;
_super.prototype._initializeShadowMap.call(this);
if (this._shadowMap === null) {
return;
}
this._transformMatricesAsArray = new Float32Array(this._numCascades * 16);
this._viewSpaceFrustumsZ = new Array(this._numCascades);
this._frustumLengths = new Array(this._numCascades);
this._lightSizeUVCorrection = new Array(this._numCascades * 2);
this._depthCorrection = new Array(this._numCascades);
this._cascades = [];
this._viewMatrices = [];
this._projectionMatrices = [];
this._transformMatrices = [];
this._cascadeMinExtents = [];
this._cascadeMaxExtents = [];
this._frustumCenter = [];
this._shadowCameraPos = [];
this._frustumCornersWorldSpace = [];
for (var cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
this._cascades[cascadeIndex] = {
prevBreakDistance: 0,
breakDistance: 0,
};
this._viewMatrices[cascadeIndex] = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero();
this._projectionMatrices[cascadeIndex] = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero();
this._transformMatrices[cascadeIndex] = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero();
this._cascadeMinExtents[cascadeIndex] = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]();
this._cascadeMaxExtents[cascadeIndex] = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]();
this._frustumCenter[cascadeIndex] = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]();
this._shadowCameraPos[cascadeIndex] = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]();
this._frustumCornersWorldSpace[cascadeIndex] = new Array(CascadedShadowGenerator.frustumCornersNDCSpace.length);
for (var i = 0; i < CascadedShadowGenerator.frustumCornersNDCSpace.length; ++i) {
this._frustumCornersWorldSpace[cascadeIndex][i] = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"]();
}
}
this._shadowMap.onBeforeRenderObservable.add(function (layer) {
_this._currentLayer = layer;
if (_this._scene.getSceneUniformBuffer().useUbo) {
var sceneUBO = _this._scene.getSceneUniformBuffer();
sceneUBO.updateMatrix("viewProjection", _this.getCascadeTransformMatrix(layer));
sceneUBO.updateMatrix("view", _this.getCascadeViewMatrix(layer));
sceneUBO.update();
}
});
this._shadowMap.onBeforeBindObservable.add(function () {
if (_this._breaksAreDirty) {
_this._splitFrustum();
}
_this._computeMatrices();
});
this._splitFrustum();
};
CascadedShadowGenerator.prototype._bindCustomEffectForRenderSubMeshForShadowMap = function (subMesh, effect, matriceNames, mesh) {
var _a, _b, _c, _d, _e, _f;
effect.setMatrix((_a = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.viewProjection) !== null && _a !== void 0 ? _a : "viewProjection", this.getCascadeTransformMatrix(this._currentLayer));
effect.setMatrix((_b = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.view) !== null && _b !== void 0 ? _b : "view", this.getCascadeViewMatrix(this._currentLayer));
effect.setMatrix((_c = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.projection) !== null && _c !== void 0 ? _c : "projection", this.getCascadeProjectionMatrix(this._currentLayer));
var world = mesh.getWorldMatrix();
effect.setMatrix((_d = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.world) !== null && _d !== void 0 ? _d : "world", world);
world.multiplyToRef(this.getCascadeTransformMatrix(this._currentLayer), tmpMatrix);
effect.setMatrix((_e = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.worldViewProjection) !== null && _e !== void 0 ? _e : "worldViewProjection", tmpMatrix);
world.multiplyToRef(this.getCascadeViewMatrix(this._currentLayer), tmpMatrix2);
effect.setMatrix((_f = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.worldView) !== null && _f !== void 0 ? _f : "worldView", tmpMatrix2);
};
CascadedShadowGenerator.prototype._isReadyCustomDefines = function (defines, subMesh, useInstances) {
defines.push("#define SM_DEPTHCLAMP " + (this._depthClamp && this._filter !== _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_PCSS ? "1" : "0"));
};
/**
* Prepare all the defines in a material relying on a shadow map at the specified light index.
* @param defines Defines of the material we want to update
* @param lightIndex Index of the light in the enabled light list of the material
*/
CascadedShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
_super.prototype.prepareDefines.call(this, defines, lightIndex);
var scene = this._scene;
var light = this._light;
if (!scene.shadowsEnabled || !light.shadowEnabled) {
return;
}
defines["SHADOWCSM" + lightIndex] = true;
defines["SHADOWCSMDEBUG" + lightIndex] = this.debug;
defines["SHADOWCSMNUM_CASCADES" + lightIndex] = this.numCascades;
defines["SHADOWCSM_RIGHTHANDED" + lightIndex] = scene.useRightHandedSystem;
var camera = scene.activeCamera;
if (camera && this._shadowMaxZ < camera.maxZ) {
defines["SHADOWCSMUSESHADOWMAXZ" + lightIndex] = true;
}
if (this.cascadeBlendPercentage === 0) {
defines["SHADOWCSMNOBLEND" + lightIndex] = true;
}
};
/**
* Binds the shadow related information inside of an effect (information like near, far, darkness...
* defined in the generator but impacting the effect).
* @param lightIndex Index of the light in the enabled light list of the material owning the effect
* @param effect The effect we are binfing the information for
*/
CascadedShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
var light = this._light;
var scene = this._scene;
if (!scene.shadowsEnabled || !light.shadowEnabled) {
return;
}
var camera = scene.activeCamera;
if (!camera) {
return;
}
var shadowMap = this.getShadowMap();
if (!shadowMap) {
return;
}
var width = shadowMap.getSize().width;
effect.setMatrices("lightMatrix" + lightIndex, this._transformMatricesAsArray);
effect.setArray("viewFrustumZ" + lightIndex, this._viewSpaceFrustumsZ);
effect.setFloat("cascadeBlendFactor" + lightIndex, this.cascadeBlendPercentage === 0 ? 10000 : 1 / this.cascadeBlendPercentage);
effect.setArray("frustumLengths" + lightIndex, this._frustumLengths);
// Only PCF uses depth stencil texture.
if (this._filter === _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_PCF) {
effect.setDepthStencilTexture("shadowSampler" + lightIndex, shadowMap);
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
}
else if (this._filter === _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].FILTER_PCSS) {
for (var cascadeIndex = 0; cascadeIndex < this._numCascades; ++cascadeIndex) {
this._lightSizeUVCorrection[cascadeIndex * 2 + 0] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].x - this._cascadeMinExtents[0].x) / (this._cascadeMaxExtents[cascadeIndex].x - this._cascadeMinExtents[cascadeIndex].x); // x correction
this._lightSizeUVCorrection[cascadeIndex * 2 + 1] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[0].y - this._cascadeMinExtents[0].y) / (this._cascadeMaxExtents[cascadeIndex].y - this._cascadeMinExtents[cascadeIndex].y); // y correction
this._depthCorrection[cascadeIndex] = cascadeIndex === 0 ? 1 : (this._cascadeMaxExtents[cascadeIndex].z - this._cascadeMinExtents[cascadeIndex].z) / (this._cascadeMaxExtents[0].z - this._cascadeMinExtents[0].z);
}
effect.setDepthStencilTexture("shadowSampler" + lightIndex, shadowMap);
effect.setTexture("depthSampler" + lightIndex, shadowMap);
effect.setArray2("lightSizeUVCorrection" + lightIndex, this._lightSizeUVCorrection);
effect.setArray("depthCorrection" + lightIndex, this._depthCorrection);
effect.setFloat("penumbraDarkness" + lightIndex, this.penumbraDarkness);
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / width, this._contactHardeningLightSizeUVRatio * width, this.frustumEdgeFalloff, lightIndex);
}
else {
effect.setTexture("shadowSampler" + lightIndex, shadowMap);
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), width, 1 / width, this.frustumEdgeFalloff, lightIndex);
}
light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
};
/**
* Gets the transformation matrix of the first cascade used to project the meshes into the map from the light point of view.
* (eq to view projection * shadow projection matrices)
* @returns The transform matrix used to create the shadow map
*/
CascadedShadowGenerator.prototype.getTransformMatrix = function () {
return this.getCascadeTransformMatrix(0);
};
/**
* Disposes the ShadowGenerator.
* Returns nothing.
*/
CascadedShadowGenerator.prototype.dispose = function () {
_super.prototype.dispose.call(this);
if (this._freezeShadowCastersBoundingInfoObservable) {
this._scene.onBeforeRenderObservable.remove(this._freezeShadowCastersBoundingInfoObservable);
this._freezeShadowCastersBoundingInfoObservable = null;
}
if (this._depthReducer) {
this._depthReducer.dispose();
this._depthReducer = null;
}
};
/**
* Serializes the shadow generator setup to a json object.
* @returns The serialized JSON object
*/
CascadedShadowGenerator.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
var shadowMap = this.getShadowMap();
if (!shadowMap) {
return serializationObject;
}
serializationObject.numCascades = this._numCascades;
serializationObject.debug = this._debug;
serializationObject.stabilizeCascades = this.stabilizeCascades;
serializationObject.lambda = this._lambda;
serializationObject.cascadeBlendPercentage = this.cascadeBlendPercentage;
serializationObject.depthClamp = this._depthClamp;
serializationObject.autoCalcDepthBounds = this.autoCalcDepthBounds;
serializationObject.shadowMaxZ = this._shadowMaxZ;
serializationObject.penumbraDarkness = this.penumbraDarkness;
serializationObject.freezeShadowCastersBoundingInfo = this._freezeShadowCastersBoundingInfo;
serializationObject.minDistance = this.minDistance;
serializationObject.maxDistance = this.maxDistance;
serializationObject.renderList = [];
if (shadowMap.renderList) {
for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
var mesh = shadowMap.renderList[meshIndex];
serializationObject.renderList.push(mesh.id);
}
}
return serializationObject;
};
/**
* Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
* @param parsedShadowGenerator The JSON object to parse
* @param scene The scene to create the shadow map for
* @returns The parsed shadow generator
*/
CascadedShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
var shadowGenerator = _shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"].Parse(parsedShadowGenerator, scene, function (mapSize, light) { return new CascadedShadowGenerator(mapSize, light); });
if (parsedShadowGenerator.numCascades !== undefined) {
shadowGenerator.numCascades = parsedShadowGenerator.numCascades;
}
if (parsedShadowGenerator.debug !== undefined) {
shadowGenerator.debug = parsedShadowGenerator.debug;
}
if (parsedShadowGenerator.stabilizeCascades !== undefined) {
shadowGenerator.stabilizeCascades = parsedShadowGenerator.stabilizeCascades;
}
if (parsedShadowGenerator.lambda !== undefined) {
shadowGenerator.lambda = parsedShadowGenerator.lambda;
}
if (parsedShadowGenerator.cascadeBlendPercentage !== undefined) {
shadowGenerator.cascadeBlendPercentage = parsedShadowGenerator.cascadeBlendPercentage;
}
if (parsedShadowGenerator.depthClamp !== undefined) {
shadowGenerator.depthClamp = parsedShadowGenerator.depthClamp;
}
if (parsedShadowGenerator.autoCalcDepthBounds !== undefined) {
shadowGenerator.autoCalcDepthBounds = parsedShadowGenerator.autoCalcDepthBounds;
}
if (parsedShadowGenerator.shadowMaxZ !== undefined) {
shadowGenerator.shadowMaxZ = parsedShadowGenerator.shadowMaxZ;
}
if (parsedShadowGenerator.penumbraDarkness !== undefined) {
shadowGenerator.penumbraDarkness = parsedShadowGenerator.penumbraDarkness;
}
if (parsedShadowGenerator.freezeShadowCastersBoundingInfo !== undefined) {
shadowGenerator.freezeShadowCastersBoundingInfo = parsedShadowGenerator.freezeShadowCastersBoundingInfo;
}
if (parsedShadowGenerator.minDistance !== undefined && parsedShadowGenerator.maxDistance !== undefined) {
shadowGenerator.setMinMaxDistance(parsedShadowGenerator.minDistance, parsedShadowGenerator.maxDistance);
}
return shadowGenerator;
};
CascadedShadowGenerator.frustumCornersNDCSpace = [
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1.0, +1.0, -1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](+1.0, +1.0, -1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](+1.0, -1.0, -1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1.0, -1.0, -1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1.0, +1.0, +1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](+1.0, +1.0, +1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](+1.0, -1.0, +1.0),
new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](-1.0, -1.0, +1.0),
];
/**
* Name of the CSM class
*/
CascadedShadowGenerator.CLASSNAME = "CascadedShadowGenerator";
/**
* Defines the default number of cascades used by the CSM.
*/
CascadedShadowGenerator.DEFAULT_CASCADES_COUNT = 4;
/**
* Defines the minimum number of cascades used by the CSM.
*/
CascadedShadowGenerator.MIN_CASCADES_COUNT = 2;
/**
* Defines the maximum number of cascades used by the CSM.
*/
CascadedShadowGenerator.MAX_CASCADES_COUNT = 4;
/** @hidden */
CascadedShadowGenerator._SceneComponentInitialization = function (_) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_7__["_DevTools"].WarnImport("ShadowGeneratorSceneComponent");
};
return CascadedShadowGenerator;
}(_shadowGenerator__WEBPACK_IMPORTED_MODULE_8__["ShadowGenerator"]));
/***/ }),
/***/ "./Lights/Shadows/index.ts":
/*!*********************************!*\
!*** ./Lights/Shadows/index.ts ***!
\*********************************/
/*! exports provided: ShadowGenerator, CascadedShadowGenerator, ShadowGeneratorSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]; });
/* harmony import */ var _cascadedShadowGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cascadedShadowGenerator */ "./Lights/Shadows/cascadedShadowGenerator.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CascadedShadowGenerator", function() { return _cascadedShadowGenerator__WEBPACK_IMPORTED_MODULE_1__["CascadedShadowGenerator"]; });
/* harmony import */ var _shadowGeneratorSceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./shadowGeneratorSceneComponent */ "./Lights/Shadows/shadowGeneratorSceneComponent.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _shadowGeneratorSceneComponent__WEBPACK_IMPORTED_MODULE_2__["ShadowGeneratorSceneComponent"]; });
/***/ }),
/***/ "./Lights/Shadows/shadowGenerator.ts":
/*!*******************************************!*\
!*** ./Lights/Shadows/shadowGenerator.ts ***!
\*******************************************/
/*! exports provided: ShadowGenerator */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return ShadowGenerator; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Lights/light */ "./Lights/light.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts");
/* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts");
/* harmony import */ var _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../PostProcesses/blurPostProcess */ "./PostProcesses/blurPostProcess.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Shaders_shadowMap_fragment__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Shaders/shadowMap.fragment */ "./Shaders/shadowMap.fragment.ts");
/* harmony import */ var _Shaders_shadowMap_vertex__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Shaders/shadowMap.vertex */ "./Shaders/shadowMap.vertex.ts");
/* harmony import */ var _Shaders_depthBoxBlur_fragment__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Shaders/depthBoxBlur.fragment */ "./Shaders/depthBoxBlur.fragment.ts");
/* harmony import */ var _Shaders_ShadersInclude_shadowMapFragmentSoftTransparentShadow__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow */ "./Shaders/ShadersInclude/shadowMapFragmentSoftTransparentShadow.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Misc/devTools */ "./Misc/devTools.ts");
/* harmony import */ var _Materials_effectFallbacks__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/effectFallbacks */ "./Materials/effectFallbacks.ts");
/* harmony import */ var _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Rendering/renderingManager */ "./Rendering/renderingManager.ts");
var tmpMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"](), tmpMatrix2 = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"]();
/**
* Default implementation IShadowGenerator.
* This is the main object responsible of generating shadows in the framework.
* Documentation: https://doc.babylonjs.com/babylon101/shadows
*/
var ShadowGenerator = /** @class */ (function () {
/**
* Creates a ShadowGenerator object.
* A ShadowGenerator is the required tool to use the shadows.
* Each light casting shadows needs to use its own ShadowGenerator.
* Documentation : https://doc.babylonjs.com/babylon101/shadows
* @param mapSize The size of the texture what stores the shadows. Example : 1024.
* @param light The light object generating the shadows.
* @param usefulFloatFirst By default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
*/
function ShadowGenerator(mapSize, light, usefulFloatFirst) {
/**
* Observable triggered before the shadow is rendered. Can be used to update internal effect state
*/
this.onBeforeShadowMapRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_15__["Observable"]();
/**
* Observable triggered after the shadow is rendered. Can be used to restore internal effect state
*/
this.onAfterShadowMapRenderObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_15__["Observable"]();
/**
* Observable triggered before a mesh is rendered in the shadow map.
* Can be used to update internal effect state (that you can get from the onBeforeShadowMapRenderObservable)
*/
this.onBeforeShadowMapRenderMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_15__["Observable"]();
/**
* Observable triggered after a mesh is rendered in the shadow map.
* Can be used to update internal effect state (that you can get from the onAfterShadowMapRenderObservable)
*/
this.onAfterShadowMapRenderMeshObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_15__["Observable"]();
this._bias = 0.00005;
this._normalBias = 0;
this._blurBoxOffset = 1;
this._blurScale = 2;
this._blurKernel = 1;
this._useKernelBlur = false;
this._filter = ShadowGenerator.FILTER_NONE;
this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
this._contactHardeningLightSizeUVRatio = 0.1;
this._darkness = 0;
this._transparencyShadow = false;
/**
* Enables or disables shadows with varying strength based on the transparency
* When it is enabled, the strength of the shadow is taken equal to mesh.visibility
* If you enabled an alpha texture on your material, the alpha value red from the texture is also combined to compute the strength:
* mesh.visibility * alphaTexture.a
* Note that by definition transparencyShadow must be set to true for enableSoftTransparentShadow to work!
*/
this.enableSoftTransparentShadow = false;
/**
* Controls the extent to which the shadows fade out at the edge of the frustum
*/
this.frustumEdgeFalloff = 0;
/**
* If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
* This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
* It might on the other hand introduce peter panning.
*/
this.forceBackFacesOnly = false;
this._lightDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Zero();
this._viewMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero();
this._projectionMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero();
this._transformMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Zero();
this._cachedPosition = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._cachedDirection = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"](Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
this._currentFaceIndex = 0;
this._currentFaceIndexCache = 0;
this._defaultTextureMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].Identity();
this._mapSize = mapSize;
this._light = light;
this._scene = light.getScene();
light._shadowGenerator = this;
this.id = light.id;
ShadowGenerator._SceneComponentInitialization(this._scene);
// Texture type fallback from float to int if not supported.
var caps = this._scene.getEngine().getCaps();
if (!usefulFloatFirst) {
if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT;
}
else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_FLOAT;
}
else {
this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT;
}
}
else {
if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_FLOAT;
}
else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_HALF_FLOAT;
}
else {
this._textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT;
}
}
this._initializeGenerator();
this._applyFilterValues();
}
Object.defineProperty(ShadowGenerator.prototype, "bias", {
/**
* Gets the bias: offset applied on the depth preventing acnea (in light direction).
*/
get: function () {
return this._bias;
},
/**
* Sets the bias: offset applied on the depth preventing acnea (in light direction).
*/
set: function (bias) {
this._bias = bias;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
/**
* Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
*/
get: function () {
return this._normalBias;
},
/**
* Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
*/
set: function (normalBias) {
this._normalBias = normalBias;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
/**
* Gets the blur box offset: offset applied during the blur pass.
* Only useful if useKernelBlur = false
*/
get: function () {
return this._blurBoxOffset;
},
/**
* Sets the blur box offset: offset applied during the blur pass.
* Only useful if useKernelBlur = false
*/
set: function (value) {
if (this._blurBoxOffset === value) {
return;
}
this._blurBoxOffset = value;
this._disposeBlurPostProcesses();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
/**
* Gets the blur scale: scale of the blurred texture compared to the main shadow map.
* 2 means half of the size.
*/
get: function () {
return this._blurScale;
},
/**
* Sets the blur scale: scale of the blurred texture compared to the main shadow map.
* 2 means half of the size.
*/
set: function (value) {
if (this._blurScale === value) {
return;
}
this._blurScale = value;
this._disposeBlurPostProcesses();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
/**
* Gets the blur kernel: kernel size of the blur pass.
* Only useful if useKernelBlur = true
*/
get: function () {
return this._blurKernel;
},
/**
* Sets the blur kernel: kernel size of the blur pass.
* Only useful if useKernelBlur = true
*/
set: function (value) {
if (this._blurKernel === value) {
return;
}
this._blurKernel = value;
this._disposeBlurPostProcesses();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
/**
* Gets whether the blur pass is a kernel blur (if true) or box blur.
* Only useful in filtered mode (useBlurExponentialShadowMap...)
*/
get: function () {
return this._useKernelBlur;
},
/**
* Sets whether the blur pass is a kernel blur (if true) or box blur.
* Only useful in filtered mode (useBlurExponentialShadowMap...)
*/
set: function (value) {
if (this._useKernelBlur === value) {
return;
}
this._useKernelBlur = value;
this._disposeBlurPostProcesses();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
/**
* Gets the depth scale used in ESM mode.
*/
get: function () {
return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
},
/**
* Sets the depth scale used in ESM mode.
* This can override the scale stored on the light.
*/
set: function (value) {
this._depthScale = value;
},
enumerable: false,
configurable: true
});
ShadowGenerator.prototype._validateFilter = function (filter) {
return filter;
};
Object.defineProperty(ShadowGenerator.prototype, "filter", {
/**
* Gets the current mode of the shadow generator (normal, PCF, ESM...).
* The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
*/
get: function () {
return this._filter;
},
/**
* Sets the current mode of the shadow generator (normal, PCF, ESM...).
* The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
*/
set: function (value) {
value = this._validateFilter(value);
// Blurring the cubemap is going to be too expensive. Reverting to unblurred version
if (this._light.needCube()) {
if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
this.useExponentialShadowMap = true;
return;
}
else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
this.useCloseExponentialShadowMap = true;
return;
}
// PCF on cubemap would also be expensive
else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
this.usePoissonSampling = true;
return;
}
}
// Weblg1 fallback for PCF.
if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
if (this._scene.getEngine().webGLVersion === 1) {
this.usePoissonSampling = true;
return;
}
}
if (this._filter === value) {
return;
}
this._filter = value;
this._disposeBlurPostProcesses();
this._applyFilterValues();
this._light._markMeshesAsLightDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
/**
* Gets if the current filter is set to Poisson Sampling.
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
},
/**
* Sets the current filter to Poisson Sampling.
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_POISSONSAMPLING);
if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
/**
* Gets if the current filter is set to ESM.
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
},
/**
* Sets the current filter is to ESM.
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP);
if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
/**
* Gets if the current filter is set to filtered ESM.
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
},
/**
* Gets if the current filter is set to filtered ESM.
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP);
if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
/**
* Gets if the current filter is set to "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
},
/**
* Sets the current filter to "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP);
if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
/**
* Gets if the current filter is set to filtered "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
},
/**
* Sets the current filter to filtered "close ESM" (using the inverse of the
* exponential to prevent steep falloff artifacts).
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP);
if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
/**
* Gets if the current filter is set to "PCF" (percentage closer filtering).
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_PCF;
},
/**
* Sets the current filter to "PCF" (percentage closer filtering).
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_PCF);
if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
/**
* Gets the PCF or PCSS Quality.
* Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
*/
get: function () {
return this._filteringQuality;
},
/**
* Sets the PCF or PCSS Quality.
* Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
*/
set: function (filteringQuality) {
if (this._filteringQuality === filteringQuality) {
return;
}
this._filteringQuality = filteringQuality;
this._disposeBlurPostProcesses();
this._applyFilterValues();
this._light._markMeshesAsLightDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
/**
* Gets if the current filter is set to "PCSS" (contact hardening).
*/
get: function () {
return this.filter === ShadowGenerator.FILTER_PCSS;
},
/**
* Sets the current filter to "PCSS" (contact hardening).
*/
set: function (value) {
var filter = this._validateFilter(ShadowGenerator.FILTER_PCSS);
if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
return;
}
this.filter = (value ? filter : ShadowGenerator.FILTER_NONE);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
/**
* Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
* Using a ratio helps keeping shape stability independently of the map size.
*
* It does not account for the light projection as it was having too much
* instability during the light setup or during light position changes.
*
* Only valid if useContactHardeningShadow is true.
*/
get: function () {
return this._contactHardeningLightSizeUVRatio;
},
/**
* Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
* Using a ratio helps keeping shape stability independently of the map size.
*
* It does not account for the light projection as it was having too much
* instability during the light setup or during light position changes.
*
* Only valid if useContactHardeningShadow is true.
*/
set: function (contactHardeningLightSizeUVRatio) {
this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowGenerator.prototype, "darkness", {
/** Gets or sets the actual darkness of a shadow */
get: function () {
return this._darkness;
},
set: function (value) {
this.setDarkness(value);
},
enumerable: false,
configurable: true
});
/**
* Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
* 0 means strongest and 1 would means no shadow.
* @returns the darkness.
*/
ShadowGenerator.prototype.getDarkness = function () {
return this._darkness;
};
/**
* Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
* @param darkness The darkness value 0 means strongest and 1 would means no shadow.
* @returns the shadow generator allowing fluent coding.
*/
ShadowGenerator.prototype.setDarkness = function (darkness) {
if (darkness >= 1.0) {
this._darkness = 1.0;
}
else if (darkness <= 0.0) {
this._darkness = 0.0;
}
else {
this._darkness = darkness;
}
return this;
};
Object.defineProperty(ShadowGenerator.prototype, "transparencyShadow", {
/** Gets or sets the ability to have transparent shadow */
get: function () {
return this._transparencyShadow;
},
set: function (value) {
this.setTransparencyShadow(value);
},
enumerable: false,
configurable: true
});
/**
* Sets the ability to have transparent shadow (boolean).
* @param transparent True if transparent else False
* @returns the shadow generator allowing fluent coding
*/
ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
this._transparencyShadow = transparent;
return this;
};
/**
* Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
* @returns The render target texture if present otherwise, null
*/
ShadowGenerator.prototype.getShadowMap = function () {
return this._shadowMap;
};
/**
* Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
* @returns The render target texture if the shadow map is present otherwise, null
*/
ShadowGenerator.prototype.getShadowMapForRendering = function () {
if (this._shadowMap2) {
return this._shadowMap2;
}
return this._shadowMap;
};
/**
* Gets the class name of that object
* @returns "ShadowGenerator"
*/
ShadowGenerator.prototype.getClassName = function () {
return ShadowGenerator.CLASSNAME;
};
/**
* Helper function to add a mesh and its descendants to the list of shadow casters.
* @param mesh Mesh to add
* @param includeDescendants boolean indicating if the descendants should be added. Default to true
* @returns the Shadow Generator itself
*/
ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
var _a;
if (includeDescendants === void 0) { includeDescendants = true; }
if (!this._shadowMap) {
return this;
}
if (!this._shadowMap.renderList) {
this._shadowMap.renderList = [];
}
this._shadowMap.renderList.push(mesh);
if (includeDescendants) {
(_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
}
return this;
};
/**
* Helper function to remove a mesh and its descendants from the list of shadow casters
* @param mesh Mesh to remove
* @param includeDescendants boolean indicating if the descendants should be removed. Default to true
* @returns the Shadow Generator itself
*/
ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
if (includeDescendants === void 0) { includeDescendants = true; }
if (!this._shadowMap || !this._shadowMap.renderList) {
return this;
}
var index = this._shadowMap.renderList.indexOf(mesh);
if (index !== -1) {
this._shadowMap.renderList.splice(index, 1);
}
if (includeDescendants) {
for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
var child = _a[_i];
this.removeShadowCaster(child);
}
}
return this;
};
/**
* Returns the associated light object.
* @returns the light generating the shadow
*/
ShadowGenerator.prototype.getLight = function () {
return this._light;
};
ShadowGenerator.prototype._initializeGenerator = function () {
this._light._markMeshesAsLightDirty();
this._initializeShadowMap();
};
ShadowGenerator.prototype._createTargetRenderTexture = function () {
var engine = this._scene.getEngine();
if (engine.webGLVersion > 1) {
this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
this._shadowMap.createDepthStencilTexture(_Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].LESS, true);
}
else {
this._shadowMap = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
}
};
ShadowGenerator.prototype._initializeShadowMap = function () {
var _this = this;
this._createTargetRenderTexture();
if (this._shadowMap === null) {
return;
}
this._shadowMap.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE;
this._shadowMap.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE;
this._shadowMap.anisotropicFilteringLevel = 1;
this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE);
this._shadowMap.renderParticles = false;
this._shadowMap.ignoreCameraViewport = true;
if (this._storedUniqueId) {
this._shadowMap.uniqueId = this._storedUniqueId;
}
// Custom render function.
this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
// Force the mesh is ready funcion to true as we are double checking it
// in the custom render function. Also it prevents side effects and useless
// shader variations in DEPTHPREPASS mode.
this._shadowMap.customIsReadyFunction = function (m, r) {
return true;
};
var engine = this._scene.getEngine();
// Record Face Index before render.
this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
_this._currentFaceIndex = faceIndex;
if (_this._filter === ShadowGenerator.FILTER_PCF) {
engine.setColorWrite(false);
}
if (_this._scene.getSceneUniformBuffer().useUbo) {
var sceneUBO = _this._scene.getSceneUniformBuffer();
sceneUBO.updateMatrix("viewProjection", _this.getTransformMatrix());
sceneUBO.updateMatrix("view", _this._viewMatrix);
sceneUBO.update();
}
});
// Blur if required afer render.
this._shadowMap.onAfterUnbindObservable.add(function () {
if (_this._scene.getSceneUniformBuffer().useUbo) {
var sceneUBO = _this._scene.getSceneUniformBuffer();
sceneUBO.updateMatrix("viewProjection", _this._scene.getTransformMatrix());
sceneUBO.updateMatrix("view", _this._scene.getViewMatrix());
sceneUBO.update();
}
if (_this._filter === ShadowGenerator.FILTER_PCF) {
engine.setColorWrite(true);
}
if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
return;
}
var shadowMap = _this.getShadowMapForRendering();
if (shadowMap) {
var texture = shadowMap.getInternalTexture();
_this._scene.postProcessManager.directRender(_this._blurPostProcesses, texture, true);
engine.unBindFramebuffer(texture, true);
}
});
// Clear according to the chosen filter.
var clearZero = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color4"](0, 0, 0, 0);
var clearOne = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color4"](1.0, 1.0, 1.0, 1.0);
this._shadowMap.onClearObservable.add(function (engine) {
if (_this._filter === ShadowGenerator.FILTER_PCF) {
engine.clear(clearOne, false, true, false);
}
else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
engine.clear(clearZero, true, true, false);
}
else {
engine.clear(clearOne, true, true, false);
}
});
// Recreate on resize.
this._shadowMap.onResizeObservable.add(function (RTT) {
_this._storedUniqueId = _this._shadowMap.uniqueId;
_this._mapSize = RTT.getRenderSize();
_this._light._markMeshesAsLightDirty();
_this.recreateShadowMap();
});
// Ensures rendering groupids do not erase the depth buffer
// or we would lose the shadows information.
for (var i = _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_18__["RenderingManager"].MIN_RENDERINGGROUPS; i < _Rendering_renderingManager__WEBPACK_IMPORTED_MODULE_18__["RenderingManager"].MAX_RENDERINGGROUPS; i++) {
this._shadowMap.setRenderingAutoClearDepthStencil(i, false);
}
};
ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
var _this = this;
var engine = this._scene.getEngine();
var targetSize = this._mapSize / this.blurScale;
if (!this.useKernelBlur || this.blurScale !== 1.0) {
this._shadowMap2 = new _Materials_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_7__["RenderTargetTexture"](this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
this._shadowMap2.wrapU = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE;
this._shadowMap2.wrapV = _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].CLAMP_ADDRESSMODE;
this._shadowMap2.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE);
}
if (this.useKernelBlur) {
this._kernelBlurXPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__["BlurPostProcess"](this._light.name + "KernelBlurX", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector2"](1, 0), this.blurKernel, 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
this._kernelBlurXPostprocess.width = targetSize;
this._kernelBlurXPostprocess.height = targetSize;
this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
effect.setTexture("textureSampler", _this._shadowMap);
});
this._kernelBlurYPostprocess = new _PostProcesses_blurPostProcess__WEBPACK_IMPORTED_MODULE_9__["BlurPostProcess"](this._light.name + "KernelBlurY", new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector2"](0, 1), this.blurKernel, 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
this._kernelBlurXPostprocess.autoClear = false;
this._kernelBlurYPostprocess.autoClear = false;
if (this._textureType === _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT) {
this._kernelBlurXPostprocess.packedFloat = true;
this._kernelBlurYPostprocess.packedFloat = true;
}
this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
}
else {
this._boxBlurPostprocess = new _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_8__["PostProcess"](this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
effect.setFloat2("screenSize", targetSize, targetSize);
effect.setTexture("textureSampler", _this._shadowMap);
});
this._boxBlurPostprocess.autoClear = false;
this._blurPostProcesses = [this._boxBlurPostprocess];
}
};
ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
var index;
var engine = this._scene.getEngine();
var colorWrite = engine.getColorWrite();
if (depthOnlySubMeshes.length) {
engine.setColorWrite(false);
for (index = 0; index < depthOnlySubMeshes.length; index++) {
this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
}
engine.setColorWrite(colorWrite);
}
for (index = 0; index < opaqueSubMeshes.length; index++) {
this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
}
for (index = 0; index < alphaTestSubMeshes.length; index++) {
this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
}
if (this._transparencyShadow) {
for (index = 0; index < transparentSubMeshes.length; index++) {
this._renderSubMeshForShadowMap(transparentSubMeshes.data[index], true);
}
}
else {
for (index = 0; index < transparentSubMeshes.length; index++) {
transparentSubMeshes.data[index].getEffectiveMesh()._internalAbstractMeshDataInfo._isActiveIntermediate = false;
}
}
};
ShadowGenerator.prototype._bindCustomEffectForRenderSubMeshForShadowMap = function (subMesh, effect, matriceNames, mesh) {
var _a, _b, _c, _d, _e, _f;
effect.setMatrix((_a = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.viewProjection) !== null && _a !== void 0 ? _a : "viewProjection", this.getTransformMatrix());
effect.setMatrix((_b = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.view) !== null && _b !== void 0 ? _b : "view", this._viewMatrix);
effect.setMatrix((_c = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.projection) !== null && _c !== void 0 ? _c : "projection", this._projectionMatrix);
var world = mesh.getWorldMatrix();
effect.setMatrix((_d = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.world) !== null && _d !== void 0 ? _d : "world", world);
world.multiplyToRef(this.getTransformMatrix(), tmpMatrix);
effect.setMatrix((_e = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.worldViewProjection) !== null && _e !== void 0 ? _e : "worldViewProjection", tmpMatrix);
world.multiplyToRef(this._viewMatrix, tmpMatrix2);
effect.setMatrix((_f = matriceNames === null || matriceNames === void 0 ? void 0 : matriceNames.worldView) !== null && _f !== void 0 ? _f : "worldView", tmpMatrix2);
};
ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh, isTransparent) {
var _a, _b;
if (isTransparent === void 0) { isTransparent = false; }
var renderingMesh = subMesh.getRenderingMesh();
var effectiveMesh = subMesh.getEffectiveMesh();
var scene = this._scene;
var engine = scene.getEngine();
var material = subMesh.getMaterial();
effectiveMesh._internalAbstractMeshDataInfo._isActiveIntermediate = false;
if (!material || subMesh.verticesCount === 0) {
return;
}
// Culling
engine.setState(material.backFaceCulling);
// Managing instances
var batch = renderingMesh._getInstancesRenderList(subMesh._id, !!subMesh.getReplacementMesh());
if (batch.mustReturn) {
return;
}
var hardwareInstancedRendering = engine.getCaps().instancedArrays && (batch.visibleInstances[subMesh._id] !== null && batch.visibleInstances[subMesh._id] !== undefined || renderingMesh.hasThinInstances);
if (this.isReady(subMesh, hardwareInstancedRendering, isTransparent)) {
var shadowDepthWrapper = (_a = renderingMesh.material) === null || _a === void 0 ? void 0 : _a.shadowDepthWrapper;
var effect_1 = (_b = shadowDepthWrapper === null || shadowDepthWrapper === void 0 ? void 0 : shadowDepthWrapper.getEffect(subMesh, this)) !== null && _b !== void 0 ? _b : this._effect;
engine.enableEffect(effect_1);
renderingMesh._bind(subMesh, effect_1, material.fillMode);
this.getTransformMatrix(); // make sur _cachedDirection et _cachedPosition are up to date
effect_1.setFloat3("biasAndScaleSM", this.bias, this.normalBias, this.depthScale);
if (this.getLight().getTypeID() === _Lights_light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT) {
effect_1.setVector3("lightDataSM", this._cachedDirection);
}
else {
effect_1.setVector3("lightDataSM", this._cachedPosition);
}
if (scene.activeCamera) {
effect_1.setFloat2("depthValuesSM", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
}
if (isTransparent && this.enableSoftTransparentShadow) {
effect_1.setFloat("softTransparentShadowSM", effectiveMesh.visibility);
}
if (shadowDepthWrapper) {
subMesh._effectOverride = effect_1;
if (shadowDepthWrapper.standalone) {
shadowDepthWrapper.baseMaterial.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
}
else {
material.bindForSubMesh(effectiveMesh.getWorldMatrix(), renderingMesh, subMesh);
}
subMesh._effectOverride = null;
}
else {
effect_1.setMatrix("viewProjection", this.getTransformMatrix());
// Alpha test
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
effect_1.setTexture("diffuseSampler", alphaTexture);
effect_1.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
}
}
// Bones
if (renderingMesh.useBones && renderingMesh.computeBonesUsingShaders && renderingMesh.skeleton) {
var skeleton = renderingMesh.skeleton;
if (skeleton.isUsingTextureForMatrices) {
var boneTexture = skeleton.getTransformMatrixTexture(renderingMesh);
if (!boneTexture) {
return;
}
effect_1.setTexture("boneSampler", boneTexture);
effect_1.setFloat("boneTextureWidth", 4.0 * (skeleton.bones.length + 1));
}
else {
effect_1.setMatrices("mBones", skeleton.getTransformMatrices((renderingMesh)));
}
}
// Morph targets
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindMorphTargetParameters(renderingMesh, effect_1);
// Clip planes
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindClipPlane(effect_1, scene);
}
this._bindCustomEffectForRenderSubMeshForShadowMap(subMesh, effect_1, shadowDepthWrapper === null || shadowDepthWrapper === void 0 ? void 0 : shadowDepthWrapper._matriceNames, effectiveMesh);
if (this.forceBackFacesOnly) {
engine.setState(true, 0, false, true);
}
// Observables
this.onBeforeShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
this.onBeforeShadowMapRenderObservable.notifyObservers(effect_1);
// Draw
renderingMesh._processRendering(effectiveMesh, subMesh, effect_1, material.fillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect_1.setMatrix("world", world); });
if (this.forceBackFacesOnly) {
engine.setState(true, 0, false, false);
}
// Observables
this.onAfterShadowMapRenderObservable.notifyObservers(effect_1);
this.onAfterShadowMapRenderMeshObservable.notifyObservers(renderingMesh);
}
else {
// Need to reset refresh rate of the shadowMap
if (this._shadowMap) {
this._shadowMap.resetRefreshCounter();
}
}
};
ShadowGenerator.prototype._applyFilterValues = function () {
if (!this._shadowMap) {
return;
}
if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].NEAREST_SAMPLINGMODE);
}
else {
this._shadowMap.updateSamplingMode(_Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].BILINEAR_SAMPLINGMODE);
}
};
/**
* Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
* @param onCompiled Callback triggered at the and of the effects compilation
* @param options Sets of optional options forcing the compilation with different modes
*/
ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
var _this = this;
var localOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ useInstances: false }, options);
var shadowMap = this.getShadowMap();
if (!shadowMap) {
if (onCompiled) {
onCompiled(this);
}
return;
}
var renderList = shadowMap.renderList;
if (!renderList) {
if (onCompiled) {
onCompiled(this);
}
return;
}
var subMeshes = new Array();
for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
var mesh = renderList_1[_i];
subMeshes.push.apply(subMeshes, mesh.subMeshes);
}
if (subMeshes.length === 0) {
if (onCompiled) {
onCompiled(this);
}
return;
}
var currentIndex = 0;
var checkReady = function () {
var _a, _b;
if (!_this._scene || !_this._scene.getEngine()) {
return;
}
while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances, (_b = (_a = subMeshes[currentIndex].getMaterial()) === null || _a === void 0 ? void 0 : _a.needAlphaBlendingForMesh(subMeshes[currentIndex].getMesh())) !== null && _b !== void 0 ? _b : false)) {
currentIndex++;
if (currentIndex >= subMeshes.length) {
if (onCompiled) {
onCompiled(_this);
}
return;
}
}
setTimeout(checkReady, 16);
};
checkReady();
};
/**
* Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
* @param options Sets of optional options forcing the compilation with different modes
* @returns A promise that resolves when the compilation completes
*/
ShadowGenerator.prototype.forceCompilationAsync = function (options) {
var _this = this;
return new Promise(function (resolve) {
_this.forceCompilation(function () {
resolve();
}, options);
});
};
ShadowGenerator.prototype._isReadyCustomDefines = function (defines, subMesh, useInstances) {
};
ShadowGenerator.prototype._prepareShadowDefines = function (subMesh, useInstances, defines, isTransparent) {
defines.push("#define SM_FLOAT " + (this._textureType !== _Engines_constants__WEBPACK_IMPORTED_MODULE_10__["Constants"].TEXTURETYPE_UNSIGNED_INT ? "1" : "0"));
defines.push("#define SM_ESM " + (this.useExponentialShadowMap || this.useBlurExponentialShadowMap ? "1" : "0"));
defines.push("#define SM_DEPTHTEXTURE " + (this.usePercentageCloserFiltering || this.useContactHardeningShadow ? "1" : "0"));
var mesh = subMesh.getMesh();
// Normal bias.
defines.push("#define SM_NORMALBIAS " + (this.normalBias && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].NormalKind) ? "1" : "0"));
defines.push("#define SM_DIRECTIONINLIGHTDATA " + (this.getLight().getTypeID() === _Lights_light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT ? "1" : "0"));
// Point light
defines.push("#define SM_USEDISTANCE " + (this._light.needCube() ? "1" : "0"));
// Soft transparent shadows
defines.push("#define SM_SOFTTRANSPARENTSHADOW " + (this.enableSoftTransparentShadow && isTransparent ? "1" : "0"));
this._isReadyCustomDefines(defines, subMesh, useInstances);
return defines;
};
/**
* Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
* @param subMesh The submesh we want to render in the shadow map
* @param useInstances Defines wether will draw in the map using instances
* @param isTransparent Indicates that isReady is called for a transparent subMesh
* @returns true if ready otherwise, false
*/
ShadowGenerator.prototype.isReady = function (subMesh, useInstances, isTransparent) {
var material = subMesh.getMaterial(), shadowDepthWrapper = material === null || material === void 0 ? void 0 : material.shadowDepthWrapper;
var defines = [];
this._prepareShadowDefines(subMesh, useInstances, defines, isTransparent);
if (shadowDepthWrapper) {
if (!shadowDepthWrapper.isReadyForSubMesh(subMesh, defines, this, useInstances)) {
return false;
}
}
else {
var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].PositionKind];
var mesh = subMesh.getMesh();
// Normal bias.
if (this.normalBias && mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].NormalKind)) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].NormalKind);
defines.push("#define NORMAL");
if (mesh.nonUniformScaling) {
defines.push("#define NONUNIFORMSCALING");
}
}
// Alpha test
if (material && material.needAlphaTesting()) {
var alphaTexture = material.getAlphaTestTexture();
if (alphaTexture) {
if (!alphaTexture.isReady()) {
return false;
}
defines.push("#define ALPHATEST");
if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].UVKind)) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].UVKind);
defines.push("#define UV1");
}
if (mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].UV2Kind)) {
if (alphaTexture.coordinatesIndex === 1) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].UV2Kind);
defines.push("#define UV2");
}
}
}
}
// Bones
var fallbacks = new _Materials_effectFallbacks__WEBPACK_IMPORTED_MODULE_17__["EffectFallbacks"]();
if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].MatricesIndicesKind);
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].MatricesWeightsKind);
if (mesh.numBoneInfluencers > 4) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].MatricesIndicesExtraKind);
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_3__["VertexBuffer"].MatricesWeightsExtraKind);
}
var skeleton = mesh.skeleton;
defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
if (mesh.numBoneInfluencers > 0) {
fallbacks.addCPUSkinningFallback(0, mesh);
}
if (skeleton.isUsingTextureForMatrices) {
defines.push("#define BONETEXTURE");
}
else {
defines.push("#define BonesPerMesh " + (skeleton.bones.length + 1));
}
}
else {
defines.push("#define NUM_BONE_INFLUENCERS 0");
}
// Morph targets
var manager = mesh.morphTargetManager;
var morphInfluencers = 0;
if (manager) {
if (manager.numInfluencers > 0) {
defines.push("#define MORPHTARGETS");
morphInfluencers = manager.numInfluencers;
defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareAttributesForMorphTargetsInfluencers(attribs, mesh, morphInfluencers);
}
}
// ClipPlanes
var scene = this._scene;
if (scene.clipPlane) {
defines.push("#define CLIPPLANE");
}
if (scene.clipPlane2) {
defines.push("#define CLIPPLANE2");
}
if (scene.clipPlane3) {
defines.push("#define CLIPPLANE3");
}
if (scene.clipPlane4) {
defines.push("#define CLIPPLANE4");
}
if (scene.clipPlane5) {
defines.push("#define CLIPPLANE5");
}
if (scene.clipPlane6) {
defines.push("#define CLIPPLANE6");
}
// Instances
if (useInstances) {
defines.push("#define INSTANCES");
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PushAttributesForInstances(attribs);
if (subMesh.getRenderingMesh().hasThinInstances) {
defines.push("#define THIN_INSTANCES");
}
}
if (this.customShaderOptions) {
if (this.customShaderOptions.defines) {
for (var _i = 0, _a = this.customShaderOptions.defines; _i < _a.length; _i++) {
var define = _a[_i];
if (defines.indexOf(define) === -1) {
defines.push(define);
}
}
}
}
// Get correct effect
var join = defines.join("\n");
if (this._cachedDefines !== join) {
this._cachedDefines = join;
var shaderName = "shadowMap";
var uniforms = ["world", "mBones", "viewProjection", "diffuseMatrix", "lightDataSM", "depthValuesSM", "biasAndScaleSM", "morphTargetInfluences", "boneTextureWidth",
"vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "softTransparentShadowSM"];
var samplers = ["diffuseSampler", "boneSampler"];
// Custom shader?
if (this.customShaderOptions) {
shaderName = this.customShaderOptions.shaderName;
if (this.customShaderOptions.attributes) {
for (var _b = 0, _c = this.customShaderOptions.attributes; _b < _c.length; _b++) {
var attrib = _c[_b];
if (attribs.indexOf(attrib) === -1) {
attribs.push(attrib);
}
}
}
if (this.customShaderOptions.uniforms) {
for (var _d = 0, _e = this.customShaderOptions.uniforms; _d < _e.length; _d++) {
var uniform = _e[_d];
if (uniforms.indexOf(uniform) === -1) {
uniforms.push(uniform);
}
}
}
if (this.customShaderOptions.samplers) {
for (var _f = 0, _g = this.customShaderOptions.samplers; _f < _g.length; _f++) {
var sampler = _g[_f];
if (samplers.indexOf(sampler) === -1) {
samplers.push(sampler);
}
}
}
}
this._effect = this._scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
}
if (!this._effect.isReady()) {
return false;
}
}
if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
this._initializeBlurRTTAndPostProcesses();
}
}
if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
return false;
}
if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
return false;
}
if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
return false;
}
return true;
};
/**
* Prepare all the defines in a material relying on a shadow map at the specified light index.
* @param defines Defines of the material we want to update
* @param lightIndex Index of the light in the enabled light list of the material
*/
ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
var scene = this._scene;
var light = this._light;
if (!scene.shadowsEnabled || !light.shadowEnabled) {
return;
}
defines["SHADOW" + lightIndex] = true;
if (this.useContactHardeningShadow) {
defines["SHADOWPCSS" + lightIndex] = true;
if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
defines["SHADOWLOWQUALITY" + lightIndex] = true;
}
else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
}
// else default to high.
}
else if (this.usePercentageCloserFiltering) {
defines["SHADOWPCF" + lightIndex] = true;
if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
defines["SHADOWLOWQUALITY" + lightIndex] = true;
}
else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
}
// else default to high.
}
else if (this.usePoissonSampling) {
defines["SHADOWPOISSON" + lightIndex] = true;
}
else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
defines["SHADOWESM" + lightIndex] = true;
}
else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
defines["SHADOWCLOSEESM" + lightIndex] = true;
}
if (light.needCube()) {
defines["SHADOWCUBE" + lightIndex] = true;
}
};
/**
* Binds the shadow related information inside of an effect (information like near, far, darkness...
* defined in the generator but impacting the effect).
* @param lightIndex Index of the light in the enabled light list of the material owning the effect
* @param effect The effect we are binfing the information for
*/
ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
var light = this._light;
var scene = this._scene;
if (!scene.shadowsEnabled || !light.shadowEnabled) {
return;
}
var camera = scene.activeCamera;
if (!camera) {
return;
}
var shadowMap = this.getShadowMap();
if (!shadowMap) {
return;
}
if (!light.needCube()) {
effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
}
// Only PCF uses depth stencil texture.
if (this._filter === ShadowGenerator.FILTER_PCF) {
effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
}
else if (this._filter === ShadowGenerator.FILTER_PCSS) {
effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
}
else {
effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
}
light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
};
/**
* Gets the transformation matrix used to project the meshes into the map from the light point of view.
* (eq to shadow prjection matrix * light transform matrix)
* @returns The transform matrix used to create the shadow map
*/
ShadowGenerator.prototype.getTransformMatrix = function () {
var scene = this._scene;
if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
return this._transformMatrix;
}
this._currentRenderID = scene.getRenderId();
this._currentFaceIndexCache = this._currentFaceIndex;
var lightPosition = this._light.position;
if (this._light.computeTransformedInformation()) {
lightPosition = this._light.transformedPosition;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
if (Math.abs(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Dot(this._lightDirection, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up())) === 1.0) {
this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
}
if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
this._cachedPosition.copyFrom(lightPosition);
this._cachedDirection.copyFrom(this._lightDirection);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Matrix"].LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_1__["Vector3"].Up(), this._viewMatrix);
var shadowMap = this.getShadowMap();
if (shadowMap) {
var renderList = shadowMap.renderList;
if (renderList) {
this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
}
}
this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
}
return this._transformMatrix;
};
/**
* Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
* Cube and 2D textures for instance.
*/
ShadowGenerator.prototype.recreateShadowMap = function () {
var shadowMap = this._shadowMap;
if (!shadowMap) {
return;
}
// Track render list.
var renderList = shadowMap.renderList;
// Clean up existing data.
this._disposeRTTandPostProcesses();
// Reinitializes.
this._initializeGenerator();
// Reaffect the filter to ensure a correct fallback if necessary.
this.filter = this.filter;
// Reaffect the filter.
this._applyFilterValues();
// Reaffect Render List.
this._shadowMap.renderList = renderList;
};
ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
if (this._shadowMap2) {
this._shadowMap2.dispose();
this._shadowMap2 = null;
}
if (this._boxBlurPostprocess) {
this._boxBlurPostprocess.dispose();
this._boxBlurPostprocess = null;
}
if (this._kernelBlurXPostprocess) {
this._kernelBlurXPostprocess.dispose();
this._kernelBlurXPostprocess = null;
}
if (this._kernelBlurYPostprocess) {
this._kernelBlurYPostprocess.dispose();
this._kernelBlurYPostprocess = null;
}
this._blurPostProcesses = [];
};
ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
if (this._shadowMap) {
this._shadowMap.dispose();
this._shadowMap = null;
}
this._disposeBlurPostProcesses();
};
/**
* Disposes the ShadowGenerator.
* Returns nothing.
*/
ShadowGenerator.prototype.dispose = function () {
this._disposeRTTandPostProcesses();
if (this._light) {
this._light._shadowGenerator = null;
this._light._markMeshesAsLightDirty();
}
this.onBeforeShadowMapRenderMeshObservable.clear();
this.onBeforeShadowMapRenderObservable.clear();
this.onAfterShadowMapRenderMeshObservable.clear();
this.onAfterShadowMapRenderObservable.clear();
};
/**
* Serializes the shadow generator setup to a json object.
* @returns The serialized JSON object
*/
ShadowGenerator.prototype.serialize = function () {
var serializationObject = {};
var shadowMap = this.getShadowMap();
if (!shadowMap) {
return serializationObject;
}
serializationObject.className = this.getClassName();
serializationObject.lightId = this._light.id;
serializationObject.id = this._light.id;
serializationObject.mapSize = shadowMap.getRenderSize();
serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
serializationObject.darkness = this.getDarkness();
serializationObject.transparencyShadow = this._transparencyShadow;
serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
serializationObject.bias = this.bias;
serializationObject.normalBias = this.normalBias;
serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
serializationObject.filteringQuality = this.filteringQuality;
serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
serializationObject.usePoissonSampling = this.usePoissonSampling;
serializationObject.depthScale = this.depthScale;
serializationObject.blurBoxOffset = this.blurBoxOffset;
serializationObject.blurKernel = this.blurKernel;
serializationObject.blurScale = this.blurScale;
serializationObject.useKernelBlur = this.useKernelBlur;
serializationObject.renderList = [];
if (shadowMap.renderList) {
for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
var mesh = shadowMap.renderList[meshIndex];
serializationObject.renderList.push(mesh.id);
}
}
return serializationObject;
};
/**
* Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
* @param parsedShadowGenerator The JSON object to parse
* @param scene The scene to create the shadow map for
* @param constr A function that builds a shadow generator or undefined to create an instance of the default shadow generator
* @returns The parsed shadow generator
*/
ShadowGenerator.Parse = function (parsedShadowGenerator, scene, constr) {
var light = scene.getLightByID(parsedShadowGenerator.lightId);
var shadowGenerator = constr ? constr(parsedShadowGenerator.mapSize, light) : new ShadowGenerator(parsedShadowGenerator.mapSize, light);
var shadowMap = shadowGenerator.getShadowMap();
for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
meshes.forEach(function (mesh) {
if (!shadowMap) {
return;
}
if (!shadowMap.renderList) {
shadowMap.renderList = [];
}
shadowMap.renderList.push(mesh);
});
}
if (parsedShadowGenerator.id !== undefined) {
shadowGenerator.id = parsedShadowGenerator.id;
}
shadowGenerator.forceBackFacesOnly = !!parsedShadowGenerator.forceBackFacesOnly;
if (parsedShadowGenerator.darkness !== undefined) {
shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
}
if (parsedShadowGenerator.transparencyShadow) {
shadowGenerator.setTransparencyShadow(true);
}
if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
}
if (parsedShadowGenerator.bias !== undefined) {
shadowGenerator.bias = parsedShadowGenerator.bias;
}
if (parsedShadowGenerator.normalBias !== undefined) {
shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
}
if (parsedShadowGenerator.usePercentageCloserFiltering) {
shadowGenerator.usePercentageCloserFiltering = true;
}
else if (parsedShadowGenerator.useContactHardeningShadow) {
shadowGenerator.useContactHardeningShadow = true;
}
else if (parsedShadowGenerator.usePoissonSampling) {
shadowGenerator.usePoissonSampling = true;
}
else if (parsedShadowGenerator.useExponentialShadowMap) {
shadowGenerator.useExponentialShadowMap = true;
}
else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
shadowGenerator.useBlurExponentialShadowMap = true;
}
else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
shadowGenerator.useCloseExponentialShadowMap = true;
}
else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
shadowGenerator.useBlurCloseExponentialShadowMap = true;
}
else
// Backward compat
if (parsedShadowGenerator.useVarianceShadowMap) {
shadowGenerator.useExponentialShadowMap = true;
}
else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
shadowGenerator.useBlurExponentialShadowMap = true;
}
if (parsedShadowGenerator.contactHardeningLightSizeUVRatio !== undefined) {
shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
}
if (parsedShadowGenerator.filteringQuality !== undefined) {
shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
}
if (parsedShadowGenerator.depthScale) {
shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
}
if (parsedShadowGenerator.blurScale) {
shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
}
if (parsedShadowGenerator.blurBoxOffset) {
shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
}
if (parsedShadowGenerator.useKernelBlur) {
shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
}
if (parsedShadowGenerator.blurKernel) {
shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
}
return shadowGenerator;
};
/**
* Name of the shadow generator class
*/
ShadowGenerator.CLASSNAME = "ShadowGenerator";
/**
* Shadow generator mode None: no filtering applied.
*/
ShadowGenerator.FILTER_NONE = 0;
/**
* Shadow generator mode ESM: Exponential Shadow Mapping.
* (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
*/
ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
/**
* Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
* (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
*/
ShadowGenerator.FILTER_POISSONSAMPLING = 2;
/**
* Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
* (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
*/
ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
/**
* Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
* edge artifacts on steep falloff.
* (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
*/
ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
/**
* Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
* edge artifacts on steep falloff.
* (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
*/
ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
/**
* Shadow generator mode PCF: Percentage Closer Filtering
* benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
* (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
*/
ShadowGenerator.FILTER_PCF = 6;
/**
* Shadow generator mode PCSS: Percentage Closering Soft Shadow.
* benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
* Contact Hardening
*/
ShadowGenerator.FILTER_PCSS = 7;
/**
* Reserved for PCF and PCSS
* Highest Quality.
*
* Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
*
* Execute PCSS with 32 taps blocker search and 64 taps PCF.
*/
ShadowGenerator.QUALITY_HIGH = 0;
/**
* Reserved for PCF and PCSS
* Good tradeoff for quality/perf cross devices
*
* Execute PCF on a 3*3 kernel.
*
* Execute PCSS with 16 taps blocker search and 32 taps PCF.
*/
ShadowGenerator.QUALITY_MEDIUM = 1;
/**
* Reserved for PCF and PCSS
* The lowest quality but the fastest.
*
* Execute PCF on a 1*1 kernel.
*
* Execute PCSS with 16 taps blocker search and 16 taps PCF.
*/
ShadowGenerator.QUALITY_LOW = 2;
/** @hidden */
ShadowGenerator._SceneComponentInitialization = function (_) {
throw _Misc_devTools__WEBPACK_IMPORTED_MODULE_16__["_DevTools"].WarnImport("ShadowGeneratorSceneComponent");
};
return ShadowGenerator;
}());
/***/ }),
/***/ "./Lights/Shadows/shadowGeneratorSceneComponent.ts":
/*!*********************************************************!*\
!*** ./Lights/Shadows/shadowGeneratorSceneComponent.ts ***!
\*********************************************************/
/*! exports provided: ShadowGeneratorSceneComponent */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return ShadowGeneratorSceneComponent; });
/* harmony import */ var _shadowGenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./shadowGenerator */ "./Lights/Shadows/shadowGenerator.ts");
/* harmony import */ var _cascadedShadowGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./cascadedShadowGenerator */ "./Lights/Shadows/cascadedShadowGenerator.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../abstractScene */ "./abstractScene.ts");
// Adds the parser to the scene parsers.
_abstractScene__WEBPACK_IMPORTED_MODULE_3__["AbstractScene"].AddParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_2__["SceneComponentConstants"].NAME_SHADOWGENERATOR, function (parsedData, scene) {
// Shadows
if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
var parsedShadowGenerator = parsedData.shadowGenerators[index];
if (parsedShadowGenerator.className === _cascadedShadowGenerator__WEBPACK_IMPORTED_MODULE_1__["CascadedShadowGenerator"].CLASSNAME) {
_cascadedShadowGenerator__WEBPACK_IMPORTED_MODULE_1__["CascadedShadowGenerator"].Parse(parsedShadowGenerator, scene);
}
else {
_shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"].Parse(parsedShadowGenerator, scene);
}
// SG would be available on their associated lights
}
}
});
/**
* Defines the shadow generator component responsible to manage any shadow generators
* in a given scene.
*/
var ShadowGeneratorSceneComponent = /** @class */ (function () {
/**
* Creates a new instance of the component for the given scene
* @param scene Defines the scene to register the component in
*/
function ShadowGeneratorSceneComponent(scene) {
/**
* The component name helpfull to identify the component in the list of scene components.
*/
this.name = _sceneComponent__WEBPACK_IMPORTED_MODULE_2__["SceneComponentConstants"].NAME_SHADOWGENERATOR;
this.scene = scene;
}
/**
* Registers the component in a given scene
*/
ShadowGeneratorSceneComponent.prototype.register = function () {
this.scene._gatherRenderTargetsStage.registerStep(_sceneComponent__WEBPACK_IMPORTED_MODULE_2__["SceneComponentConstants"].STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
ShadowGeneratorSceneComponent.prototype.rebuild = function () {
// Nothing To Do Here.
};
/**
* Serializes the component data to the specified json object
* @param serializationObject The object to serialize to
*/
ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
// Shadows
serializationObject.shadowGenerators = [];
var lights = this.scene.lights;
for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
var light = lights_1[_i];
var shadowGenerator = light.getShadowGenerator();
if (shadowGenerator) {
serializationObject.shadowGenerators.push(shadowGenerator.serialize());
}
}
};
/**
* Adds all the elements from the container to the scene
* @param container the container holding the elements
*/
ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
// Nothing To Do Here. (directly attached to a light)
};
/**
* Removes all the elements in the container from the scene
* @param container contains the elements to remove
* @param dispose if the removed element should be disposed (default: false)
*/
ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container, dispose) {
// Nothing To Do Here. (directly attached to a light)
};
/**
* Rebuilds the elements related to this component in case of
* context lost for instance.
*/
ShadowGeneratorSceneComponent.prototype.dispose = function () {
// Nothing To Do Here.
};
ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
// Shadows
var scene = this.scene;
if (this.scene.shadowsEnabled) {
for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
var light = scene.lights[lightIndex];
var shadowGenerator = light.getShadowGenerator();
if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
var shadowMap = (shadowGenerator.getShadowMap());
if (scene.textures.indexOf(shadowMap) !== -1) {
renderTargets.push(shadowMap);
}
}
}
}
};
return ShadowGeneratorSceneComponent;
}());
_shadowGenerator__WEBPACK_IMPORTED_MODULE_0__["ShadowGenerator"]._SceneComponentInitialization = function (scene) {
var component = scene._getComponent(_sceneComponent__WEBPACK_IMPORTED_MODULE_2__["SceneComponentConstants"].NAME_SHADOWGENERATOR);
if (!component) {
component = new ShadowGeneratorSceneComponent(scene);
scene._addComponent(component);
}
};
/***/ }),
/***/ "./Lights/directionalLight.ts":
/*!************************************!*\
!*** ./Lights/directionalLight.ts ***!
\************************************/
/*! exports provided: DirectionalLight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return DirectionalLight; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts");
/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_1", function (name, scene) {
return function () { return new DirectionalLight(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
/**
* A directional light is defined by a direction (what a surprise!).
* The light is emitted from everywhere in the specified direction, and has an infinite range.
* An example of a directional light is when a distance planet is lit by the apparently parallel lines of light from its sun. Light in a downward direction will light the top of an object.
* Documentation: https://doc.babylonjs.com/babylon101/lights
*/
var DirectionalLight = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DirectionalLight, _super);
/**
* Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
* The directional light is emitted from everywhere in the given direction.
* It can cast shadows.
* Documentation : https://doc.babylonjs.com/babylon101/lights
* @param name The friendly name of the light
* @param direction The direction of the light
* @param scene The scene the light belongs to
*/
function DirectionalLight(name, direction, scene) {
var _this = _super.call(this, name, scene) || this;
_this._shadowFrustumSize = 0;
_this._shadowOrthoScale = 0.1;
/**
* Automatically compute the projection matrix to best fit (including all the casters)
* on each frame.
*/
_this.autoUpdateExtends = true;
/**
* Automatically compute the shadowMinZ and shadowMaxZ for the projection matrix to best fit (including all the casters)
* on each frame. autoUpdateExtends must be set to true for this to work
*/
_this.autoCalcShadowZBounds = false;
// Cache
_this._orthoLeft = Number.MAX_VALUE;
_this._orthoRight = Number.MIN_VALUE;
_this._orthoTop = Number.MIN_VALUE;
_this._orthoBottom = Number.MAX_VALUE;
_this.position = direction.scale(-1.0);
_this.direction = direction;
return _this;
}
Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
/**
* Fix frustum size for the shadow generation. This is disabled if the value is 0.
*/
get: function () {
return this._shadowFrustumSize;
},
/**
* Specifies a fix frustum size for the shadow generation.
*/
set: function (value) {
this._shadowFrustumSize = value;
this.forceProjectionMatrixCompute();
},
enumerable: false,
configurable: true
});
Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
/**
* Gets the shadow projection scale against the optimal computed one.
* 0.1 by default which means that the projection window is increase by 10% from the optimal size.
* This does not impact in fixed frustum size (shadowFrustumSize being set)
*/
get: function () {
return this._shadowOrthoScale;
},
/**
* Sets the shadow projection scale against the optimal computed one.
* 0.1 by default which means that the projection window is increase by 10% from the optimal size.
* This does not impact in fixed frustum size (shadowFrustumSize being set)
*/
set: function (value) {
this._shadowOrthoScale = value;
this.forceProjectionMatrixCompute();
},
enumerable: false,
configurable: true
});
/**
* Returns the string "DirectionalLight".
* @return The class name
*/
DirectionalLight.prototype.getClassName = function () {
return "DirectionalLight";
};
/**
* Returns the integer 1.
* @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
*/
DirectionalLight.prototype.getTypeID = function () {
return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT;
};
/**
* Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
* Returns the DirectionalLight Shadow projection matrix.
*/
DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
if (this.shadowFrustumSize > 0) {
this._setDefaultFixedFrustumShadowProjectionMatrix(matrix);
}
else {
this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
}
};
/**
* Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
* Returns the DirectionalLight Shadow projection matrix.
*/
DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
};
/**
* Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
* Returns the DirectionalLight Shadow projection matrix.
*/
DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
// Check extends
if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
var tempVector3 = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
this._orthoLeft = Number.MAX_VALUE;
this._orthoRight = Number.MIN_VALUE;
this._orthoTop = Number.MIN_VALUE;
this._orthoBottom = Number.MAX_VALUE;
var shadowMinZ = Number.MAX_VALUE;
var shadowMaxZ = Number.MIN_VALUE;
for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
var mesh = renderList[meshIndex];
if (!mesh) {
continue;
}
var boundingInfo = mesh.getBoundingInfo();
var boundingBox = boundingInfo.boundingBox;
for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
if (tempVector3.x < this._orthoLeft) {
this._orthoLeft = tempVector3.x;
}
if (tempVector3.y < this._orthoBottom) {
this._orthoBottom = tempVector3.y;
}
if (tempVector3.x > this._orthoRight) {
this._orthoRight = tempVector3.x;
}
if (tempVector3.y > this._orthoTop) {
this._orthoTop = tempVector3.y;
}
if (this.autoCalcShadowZBounds) {
if (tempVector3.z < shadowMinZ) {
shadowMinZ = tempVector3.z;
}
if (tempVector3.z > shadowMaxZ) {
shadowMaxZ = tempVector3.z;
}
}
}
}
if (this.autoCalcShadowZBounds) {
this._shadowMinZ = shadowMinZ;
this._shadowMaxZ = shadowMaxZ;
}
}
var xOffset = this._orthoRight - this._orthoLeft;
var yOffset = this._orthoTop - this._orthoBottom;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
};
DirectionalLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 4);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
* @param effect The effect to update
* @param lightIndex The index of the light in the effect to update
* @returns The directional light
*/
DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
return this;
}
this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
return this;
};
DirectionalLight.prototype.transferToNodeMaterialEffect = function (effect, lightDataUniformName) {
if (this.computeTransformedInformation()) {
effect.setFloat3(lightDataUniformName, this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z);
return this;
}
effect.setFloat3(lightDataUniformName, this.direction.x, this.direction.y, this.direction.z);
return this;
};
/**
* Gets the minZ used for shadow according to both the scene and the light.
*
* Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
* -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
* @param activeCamera The camera we are returning the min for
* @returns the depth min z
*/
DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
return 1;
};
/**
* Gets the maxZ used for shadow according to both the scene and the light.
*
* Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
* -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
* @param activeCamera The camera we are returning the max for
* @returns the depth max z
*/
DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
return 1;
};
/**
* Prepares the list of defines specific to the light type.
* @param defines the list of defines
* @param lightIndex defines the index of the light for the effect
*/
DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
defines["DIRLIGHT" + lightIndex] = true;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], DirectionalLight.prototype, "shadowFrustumSize", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], DirectionalLight.prototype, "shadowOrthoScale", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], DirectionalLight.prototype, "autoUpdateExtends", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], DirectionalLight.prototype, "autoCalcShadowZBounds", void 0);
return DirectionalLight;
}(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"]));
/***/ }),
/***/ "./Lights/hemisphericLight.ts":
/*!************************************!*\
!*** ./Lights/hemisphericLight.ts ***!
\************************************/
/*! exports provided: HemisphericLight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return HemisphericLight; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./light */ "./Lights/light.ts");
_node__WEBPACK_IMPORTED_MODULE_4__["Node"].AddNodeConstructor("Light_Type_3", function (name, scene) {
return function () { return new HemisphericLight(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
/**
* The HemisphericLight simulates the ambient environment light,
* so the passed direction is the light reflection direction, not the incoming direction.
*/
var HemisphericLight = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(HemisphericLight, _super);
/**
* Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
* The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
* The HemisphericLight can't cast shadows.
* Documentation : https://doc.babylonjs.com/babylon101/lights
* @param name The friendly name of the light
* @param direction The direction of the light reflection
* @param scene The scene the light belongs to
*/
function HemisphericLight(name, direction, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* The groundColor is the light in the opposite direction to the one specified during creation.
* You can think of the diffuse and specular light as coming from the centre of the object in the given direction and the groundColor light in the opposite direction.
*/
_this.groundColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0.0, 0.0, 0.0);
_this.direction = direction || _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up();
return _this;
}
HemisphericLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 4);
this._uniformBuffer.addUniform("vLightGround", 3);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Returns the string "HemisphericLight".
* @return The class name
*/
HemisphericLight.prototype.getClassName = function () {
return "HemisphericLight";
};
/**
* Sets the HemisphericLight direction towards the passed target (Vector3).
* Returns the updated direction.
* @param target The target the direction should point to
* @return The computed direction
*/
HemisphericLight.prototype.setDirectionToTarget = function (target) {
this.direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(target.subtract(_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero()));
return this.direction;
};
/**
* Returns the shadow generator associated to the light.
* @returns Always null for hemispheric lights because it does not support shadows.
*/
HemisphericLight.prototype.getShadowGenerator = function () {
return null;
};
/**
* Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
* @param effect The effect to update
* @param lightIndex The index of the light in the effect to update
* @returns The hemispheric light
*/
HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
var normalizeDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction);
this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
return this;
};
HemisphericLight.prototype.transferToNodeMaterialEffect = function (effect, lightDataUniformName) {
var normalizeDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction);
effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);
return this;
};
/**
* Computes the world matrix of the node
* @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
* @param useWasUpdatedFlag defines a reserved property
* @returns the world matrix
*/
HemisphericLight.prototype.computeWorldMatrix = function () {
if (!this._worldMatrix) {
this._worldMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity();
}
return this._worldMatrix;
};
/**
* Returns the integer 3.
* @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
*/
HemisphericLight.prototype.getTypeID = function () {
return _light__WEBPACK_IMPORTED_MODULE_5__["Light"].LIGHTTYPEID_HEMISPHERICLIGHT;
};
/**
* Prepares the list of defines specific to the light type.
* @param defines the list of defines
* @param lightIndex defines the index of the light for the effect
*/
HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
defines["HEMILIGHT" + lightIndex] = true;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], HemisphericLight.prototype, "groundColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], HemisphericLight.prototype, "direction", void 0);
return HemisphericLight;
}(_light__WEBPACK_IMPORTED_MODULE_5__["Light"]));
/***/ }),
/***/ "./Lights/index.ts":
/*!*************************!*\
!*** ./Lights/index.ts ***!
\*************************/
/*! exports provided: Light, ShadowLight, ShadowGenerator, CascadedShadowGenerator, ShadowGeneratorSceneComponent, DirectionalLight, HemisphericLight, PointLight, SpotLight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./light */ "./Lights/light.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return _light__WEBPACK_IMPORTED_MODULE_0__["Light"]; });
/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return _shadowLight__WEBPACK_IMPORTED_MODULE_1__["ShadowLight"]; });
/* harmony import */ var _Shadows_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Shadows/index */ "./Lights/Shadows/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGenerator", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["ShadowGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CascadedShadowGenerator", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["CascadedShadowGenerator"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ShadowGeneratorSceneComponent", function() { return _Shadows_index__WEBPACK_IMPORTED_MODULE_2__["ShadowGeneratorSceneComponent"]; });
/* harmony import */ var _directionalLight__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./directionalLight */ "./Lights/directionalLight.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DirectionalLight", function() { return _directionalLight__WEBPACK_IMPORTED_MODULE_3__["DirectionalLight"]; });
/* harmony import */ var _hemisphericLight__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./hemisphericLight */ "./Lights/hemisphericLight.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "HemisphericLight", function() { return _hemisphericLight__WEBPACK_IMPORTED_MODULE_4__["HemisphericLight"]; });
/* harmony import */ var _pointLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./pointLight */ "./Lights/pointLight.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return _pointLight__WEBPACK_IMPORTED_MODULE_5__["PointLight"]; });
/* harmony import */ var _spotLight__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./spotLight */ "./Lights/spotLight.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return _spotLight__WEBPACK_IMPORTED_MODULE_6__["SpotLight"]; });
/***/ }),
/***/ "./Lights/light.ts":
/*!*************************!*\
!*** ./Lights/light.ts ***!
\*************************/
/*! exports provided: Light */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Light", function() { return Light; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Materials/uniformBuffer */ "./Materials/uniformBuffer.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Base class of all the lights in Babylon. It groups all the generic information about lights.
* Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
* All meshes allow light to pass through them unless shadow generation is activated. The default number of lights allowed is four but this can be increased.
*/
var Light = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Light, _super);
/**
* Creates a Light object in the scene.
* Documentation : https://doc.babylonjs.com/babylon101/lights
* @param name The firendly name of the light
* @param scene The scene the light belongs too
*/
function Light(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Diffuse gives the basic color to an object.
*/
_this.diffuse = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](1.0, 1.0, 1.0);
/**
* Specular produces a highlight color on an object.
* Note: This is note affecting PBR materials.
*/
_this.specular = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](1.0, 1.0, 1.0);
/**
* Defines the falloff type for this light. This lets overrriding how punctual light are
* falling off base on range or angle.
* This can be set to any values in Light.FALLOFF_x.
*
* Note: This is only useful for PBR Materials at the moment. This could be extended if required to
* other types of materials.
*/
_this.falloffType = Light.FALLOFF_DEFAULT;
/**
* Strength of the light.
* Note: By default it is define in the framework own unit.
* Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
*/
_this.intensity = 1.0;
_this._range = Number.MAX_VALUE;
_this._inverseSquaredRange = 0;
/**
* Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
* of light.
*/
_this._photometricScale = 1.0;
_this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
_this._radius = 0.00001;
/**
* Defines the rendering priority of the lights. It can help in case of fallback or number of lights
* exceeding the number allowed of the materials.
*/
_this.renderPriority = 0;
_this._shadowEnabled = true;
_this._excludeWithLayerMask = 0;
_this._includeOnlyWithLayerMask = 0;
_this._lightmapMode = 0;
/**
* @hidden Internal use only.
*/
_this._excludedMeshesIds = new Array();
/**
* @hidden Internal use only.
*/
_this._includedOnlyMeshesIds = new Array();
/** @hidden */
_this._isLight = true;
_this.getScene().addLight(_this);
_this._uniformBuffer = new _Materials_uniformBuffer__WEBPACK_IMPORTED_MODULE_5__["UniformBuffer"](_this.getScene().getEngine());
_this._buildUniformLayout();
_this.includedOnlyMeshes = new Array();
_this.excludedMeshes = new Array();
_this._resyncMeshes();
return _this;
}
Object.defineProperty(Light.prototype, "range", {
/**
* Defines how far from the source the light is impacting in scene units.
* Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
*/
get: function () {
return this._range;
},
/**
* Defines how far from the source the light is impacting in scene units.
* Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
*/
set: function (value) {
this._range = value;
this._inverseSquaredRange = 1.0 / (this.range * this.range);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "intensityMode", {
/**
* Gets the photometric scale used to interpret the intensity.
* This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
*/
get: function () {
return this._intensityMode;
},
/**
* Sets the photometric scale used to interpret the intensity.
* This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
*/
set: function (value) {
this._intensityMode = value;
this._computePhotometricScale();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "radius", {
/**
* Gets the light radius used by PBR Materials to simulate soft area lights.
*/
get: function () {
return this._radius;
},
/**
* sets the light radius used by PBR Materials to simulate soft area lights.
*/
set: function (value) {
this._radius = value;
this._computePhotometricScale();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "shadowEnabled", {
/**
* Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
* the current shadow generator.
*/
get: function () {
return this._shadowEnabled;
},
/**
* Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
* the current shadow generator.
*/
set: function (value) {
if (this._shadowEnabled === value) {
return;
}
this._shadowEnabled = value;
this._markMeshesAsLightDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
/**
* Gets the only meshes impacted by this light.
*/
get: function () {
return this._includedOnlyMeshes;
},
/**
* Sets the only meshes impacted by this light.
*/
set: function (value) {
this._includedOnlyMeshes = value;
this._hookArrayForIncludedOnly(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "excludedMeshes", {
/**
* Gets the meshes not impacted by this light.
*/
get: function () {
return this._excludedMeshes;
},
/**
* Sets the meshes not impacted by this light.
*/
set: function (value) {
this._excludedMeshes = value;
this._hookArrayForExcluded(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
/**
* Gets the layer id use to find what meshes are not impacted by the light.
* Inactive if 0
*/
get: function () {
return this._excludeWithLayerMask;
},
/**
* Sets the layer id use to find what meshes are not impacted by the light.
* Inactive if 0
*/
set: function (value) {
this._excludeWithLayerMask = value;
this._resyncMeshes();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
/**
* Gets the layer id use to find what meshes are impacted by the light.
* Inactive if 0
*/
get: function () {
return this._includeOnlyWithLayerMask;
},
/**
* Sets the layer id use to find what meshes are impacted by the light.
* Inactive if 0
*/
set: function (value) {
this._includeOnlyWithLayerMask = value;
this._resyncMeshes();
},
enumerable: false,
configurable: true
});
Object.defineProperty(Light.prototype, "lightmapMode", {
/**
* Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
*/
get: function () {
return this._lightmapMode;
},
/**
* Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
*/
set: function (value) {
if (this._lightmapMode === value) {
return;
}
this._lightmapMode = value;
this._markMeshesAsLightDirty();
},
enumerable: false,
configurable: true
});
/**
* Sets the passed Effect "effect" with the Light textures.
* @param effect The effect to update
* @param lightIndex The index of the light in the effect to update
* @returns The light
*/
Light.prototype.transferTexturesToEffect = function (effect, lightIndex) {
// Do nothing by default.
return this;
};
/**
* Binds the lights information from the scene to the effect for the given mesh.
* @param lightIndex Light index
* @param scene The scene where the light belongs to
* @param effect The effect we are binding the data to
* @param useSpecular Defines if specular is supported
* @param rebuildInParallel Specifies whether the shader is rebuilding in parallel
*/
Light.prototype._bindLight = function (lightIndex, scene, effect, useSpecular, rebuildInParallel) {
if (rebuildInParallel === void 0) { rebuildInParallel = false; }
var iAsString = lightIndex.toString();
var needUpdate = false;
if (rebuildInParallel && this._uniformBuffer._alreadyBound) {
return;
}
this._uniformBuffer.bindToEffect(effect, "Light" + iAsString);
if (this._renderId !== scene.getRenderId() || !this._uniformBuffer.useUbo) {
this._renderId = scene.getRenderId();
var scaledIntensity = this.getScaledIntensity();
this.transferToEffect(effect, iAsString);
this.diffuse.scaleToRef(scaledIntensity, _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["TmpColors"].Color3[0]);
this._uniformBuffer.updateColor4("vLightDiffuse", _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["TmpColors"].Color3[0], this.range, iAsString);
if (useSpecular) {
this.specular.scaleToRef(scaledIntensity, _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["TmpColors"].Color3[1]);
this._uniformBuffer.updateColor4("vLightSpecular", _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["TmpColors"].Color3[1], this.radius, iAsString);
}
needUpdate = true;
}
// Textures might still need to be rebound.
this.transferTexturesToEffect(effect, iAsString);
// Shadows
if (scene.shadowsEnabled && this.shadowEnabled) {
var shadowGenerator = this.getShadowGenerator();
if (shadowGenerator) {
shadowGenerator.bindShadowLight(iAsString, effect);
needUpdate = true;
}
}
if (needUpdate) {
this._uniformBuffer.update();
}
};
/**
* Returns the string "Light".
* @returns the class name
*/
Light.prototype.getClassName = function () {
return "Light";
};
/**
* Converts the light information to a readable string for debug purpose.
* @param fullDetails Supports for multiple levels of logging within scene loading
* @returns the human readable light info
*/
Light.prototype.toString = function (fullDetails) {
var ret = "Name: " + this.name;
ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
if (this.animations) {
for (var i = 0; i < this.animations.length; i++) {
ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
}
}
if (fullDetails) {
}
return ret;
};
/** @hidden */
Light.prototype._syncParentEnabledState = function () {
_super.prototype._syncParentEnabledState.call(this);
if (!this.isDisposed()) {
this._resyncMeshes();
}
};
/**
* Set the enabled state of this node.
* @param value - the new enabled state
*/
Light.prototype.setEnabled = function (value) {
_super.prototype.setEnabled.call(this, value);
this._resyncMeshes();
};
/**
* Returns the Light associated shadow generator if any.
* @return the associated shadow generator.
*/
Light.prototype.getShadowGenerator = function () {
return this._shadowGenerator;
};
/**
* Returns a Vector3, the absolute light position in the World.
* @returns the world space position of the light
*/
Light.prototype.getAbsolutePosition = function () {
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
};
/**
* Specifies if the light will affect the passed mesh.
* @param mesh The mesh to test against the light
* @return true the mesh is affected otherwise, false.
*/
Light.prototype.canAffectMesh = function (mesh) {
if (!mesh) {
return true;
}
if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
return false;
}
if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
return false;
}
if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
return false;
}
if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
return false;
}
return true;
};
/**
* Sort function to order lights for rendering.
* @param a First Light object to compare to second.
* @param b Second Light object to compare first.
* @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
*/
Light.CompareLightsPriority = function (a, b) {
//shadow-casting lights have priority over non-shadow-casting lights
//the renderPrioirty is a secondary sort criterion
if (a.shadowEnabled !== b.shadowEnabled) {
return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
}
return b.renderPriority - a.renderPriority;
};
/**
* Releases resources associated with this node.
* @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
* @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
*/
Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
if (this._shadowGenerator) {
this._shadowGenerator.dispose();
this._shadowGenerator = null;
}
// Animations
this.getScene().stopAnimation(this);
// Remove from meshes
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
mesh._removeLightSource(this, true);
}
this._uniformBuffer.dispose();
// Remove from scene
this.getScene().removeLight(this);
_super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
};
/**
* Returns the light type ID (integer).
* @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
*/
Light.prototype.getTypeID = function () {
return 0;
};
/**
* Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
* @returns the scaled intensity in intensity mode unit
*/
Light.prototype.getScaledIntensity = function () {
return this._photometricScale * this.intensity;
};
/**
* Returns a new Light object, named "name", from the current one.
* @param name The name of the cloned light
* @param newParent The parent of this light, if it has one
* @returns the new created light
*/
Light.prototype.clone = function (name, newParent) {
if (newParent === void 0) { newParent = null; }
var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
if (!constructor) {
return null;
}
var clonedLight = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(constructor, this);
if (newParent) {
clonedLight.parent = newParent;
}
clonedLight.setEnabled(this.isEnabled());
return clonedLight;
};
/**
* Serializes the current light into a Serialization object.
* @returns the serialized object.
*/
Light.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
// Type
serializationObject.type = this.getTypeID();
// Parent
if (this.parent) {
serializationObject.parentId = this.parent.id;
}
// Inclusion / exclusions
if (this.excludedMeshes.length > 0) {
serializationObject.excludedMeshesIds = [];
this.excludedMeshes.forEach(function (mesh) {
serializationObject.excludedMeshesIds.push(mesh.id);
});
}
if (this.includedOnlyMeshes.length > 0) {
serializationObject.includedOnlyMeshesIds = [];
this.includedOnlyMeshes.forEach(function (mesh) {
serializationObject.includedOnlyMeshesIds.push(mesh.id);
});
}
// Animations
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].AppendSerializedAnimations(this, serializationObject);
serializationObject.ranges = this.serializeAnimationRanges();
return serializationObject;
};
/**
* Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
* This new light is named "name" and added to the passed scene.
* @param type Type according to the types available in Light.LIGHTTYPEID_x
* @param name The friendly name of the light
* @param scene The scene the new light will belong to
* @returns the constructor function
*/
Light.GetConstructorFromName = function (type, name, scene) {
var constructorFunc = _node__WEBPACK_IMPORTED_MODULE_4__["Node"].Construct("Light_Type_" + type, name, scene);
if (constructorFunc) {
return constructorFunc;
}
// Default to no light for none present once.
return null;
};
/**
* Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
* @param parsedLight The JSON representation of the light
* @param scene The scene to create the parsed light in
* @returns the created light after parsing
*/
Light.Parse = function (parsedLight, scene) {
var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
if (!constructor) {
return null;
}
var light = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(constructor, parsedLight, scene);
// Inclusion / exclusions
if (parsedLight.excludedMeshesIds) {
light._excludedMeshesIds = parsedLight.excludedMeshesIds;
}
if (parsedLight.includedOnlyMeshesIds) {
light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
}
// Parent
if (parsedLight.parentId) {
light._waitingParentId = parsedLight.parentId;
}
// Falloff
if (parsedLight.falloffType !== undefined) {
light.falloffType = parsedLight.falloffType;
}
// Lightmaps
if (parsedLight.lightmapMode !== undefined) {
light.lightmapMode = parsedLight.lightmapMode;
}
// Animations
if (parsedLight.animations) {
for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
var parsedAnimation = parsedLight.animations[animationIndex];
var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__["_TypeStore"].GetClass("BABYLON.Animation");
if (internalClass) {
light.animations.push(internalClass.Parse(parsedAnimation));
}
}
_node__WEBPACK_IMPORTED_MODULE_4__["Node"].ParseAnimationRanges(light, parsedLight, scene);
}
if (parsedLight.autoAnimate) {
scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
}
return light;
};
Light.prototype._hookArrayForExcluded = function (array) {
var _this = this;
var oldPush = array.push;
array.push = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var result = oldPush.apply(array, items);
for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
var item = items_1[_a];
item._resyncLightSource(_this);
}
return result;
};
var oldSplice = array.splice;
array.splice = function (index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
var item = deleted_1[_i];
item._resyncLightSource(_this);
}
return deleted;
};
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var item = array_1[_i];
item._resyncLightSource(this);
}
};
Light.prototype._hookArrayForIncludedOnly = function (array) {
var _this = this;
var oldPush = array.push;
array.push = function () {
var items = [];
for (var _i = 0; _i < arguments.length; _i++) {
items[_i] = arguments[_i];
}
var result = oldPush.apply(array, items);
_this._resyncMeshes();
return result;
};
var oldSplice = array.splice;
array.splice = function (index, deleteCount) {
var deleted = oldSplice.apply(array, [index, deleteCount]);
_this._resyncMeshes();
return deleted;
};
this._resyncMeshes();
};
Light.prototype._resyncMeshes = function () {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
mesh._resyncLightSource(this);
}
};
/**
* Forces the meshes to update their light related information in their rendering used effects
* @hidden Internal Use Only
*/
Light.prototype._markMeshesAsLightDirty = function () {
for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
var mesh = _a[_i];
if (mesh.lightSources.indexOf(this) !== -1) {
mesh._markSubMeshesAsLightDirty();
}
}
};
/**
* Recomputes the cached photometric scale if needed.
*/
Light.prototype._computePhotometricScale = function () {
this._photometricScale = this._getPhotometricScale();
this.getScene().resetCachedMaterial();
};
/**
* Returns the Photometric Scale according to the light type and intensity mode.
*/
Light.prototype._getPhotometricScale = function () {
var photometricScale = 0.0;
var lightTypeID = this.getTypeID();
//get photometric mode
var photometricMode = this.intensityMode;
if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
}
else {
photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
}
}
//compute photometric scale
switch (lightTypeID) {
case Light.LIGHTTYPEID_POINTLIGHT:
case Light.LIGHTTYPEID_SPOTLIGHT:
switch (photometricMode) {
case Light.INTENSITYMODE_LUMINOUSPOWER:
photometricScale = 1.0 / (4.0 * Math.PI);
break;
case Light.INTENSITYMODE_LUMINOUSINTENSITY:
photometricScale = 1.0;
break;
case Light.INTENSITYMODE_LUMINANCE:
photometricScale = this.radius * this.radius;
break;
}
break;
case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
switch (photometricMode) {
case Light.INTENSITYMODE_ILLUMINANCE:
photometricScale = 1.0;
break;
case Light.INTENSITYMODE_LUMINANCE:
// When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
// For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
var apexAngleRadians = this.radius;
// Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
apexAngleRadians = Math.max(apexAngleRadians, 0.001);
var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
photometricScale = solidAngle;
break;
}
break;
case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
// No fall off in hemisperic light.
photometricScale = 1.0;
break;
}
return photometricScale;
};
/**
* Reorder the light in the scene according to their defined priority.
* @hidden Internal Use Only
*/
Light.prototype._reorderLightsInScene = function () {
var scene = this.getScene();
if (this._renderPriority != 0) {
scene.requireLightSorting = true;
}
this.getScene().sortLightsByPriority();
};
/**
* Falloff Default: light is falling off following the material specification:
* standard material is using standard falloff whereas pbr material can request special falloff per materials.
*/
Light.FALLOFF_DEFAULT = 0;
/**
* Falloff Physical: light is falling off following the inverse squared distance law.
*/
Light.FALLOFF_PHYSICAL = 1;
/**
* Falloff gltf: light is falling off as described in the gltf moving to PBR document
* to enhance interoperability with other engines.
*/
Light.FALLOFF_GLTF = 2;
/**
* Falloff Standard: light is falling off like in the standard material
* to enhance interoperability with other materials.
*/
Light.FALLOFF_STANDARD = 3;
//lightmapMode Consts
/**
* If every light affecting the material is in this lightmapMode,
* material.lightmapTexture adds or multiplies
* (depends on material.useLightmapAsShadowmap)
* after every other light calculations.
*/
Light.LIGHTMAP_DEFAULT = 0;
/**
* material.lightmapTexture as only diffuse lighting from this light
* adds only specular lighting from this light
* adds dynamic shadows
*/
Light.LIGHTMAP_SPECULAR = 1;
/**
* material.lightmapTexture as only lighting
* no light calculation from this light
* only adds dynamic shadows from this light
*/
Light.LIGHTMAP_SHADOWSONLY = 2;
// Intensity Mode Consts
/**
* Each light type uses the default quantity according to its type:
* point/spot lights use luminous intensity
* directional lights use illuminance
*/
Light.INTENSITYMODE_AUTOMATIC = 0;
/**
* lumen (lm)
*/
Light.INTENSITYMODE_LUMINOUSPOWER = 1;
/**
* candela (lm/sr)
*/
Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
/**
* lux (lm/m^2)
*/
Light.INTENSITYMODE_ILLUMINANCE = 3;
/**
* nit (cd/m^2)
*/
Light.INTENSITYMODE_LUMINANCE = 4;
// Light types ids const.
/**
* Light type const id of the point light.
*/
Light.LIGHTTYPEID_POINTLIGHT = 0;
/**
* Light type const id of the directional light.
*/
Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
/**
* Light type const id of the spot light.
*/
Light.LIGHTTYPEID_SPOTLIGHT = 2;
/**
* Light type const id of the hemispheric light.
*/
Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], Light.prototype, "diffuse", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], Light.prototype, "specular", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Light.prototype, "falloffType", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Light.prototype, "intensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Light.prototype, "range", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Light.prototype, "intensityMode", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Light.prototype, "radius", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], Light.prototype, "_renderPriority", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_reorderLightsInScene")
], Light.prototype, "renderPriority", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("shadowEnabled")
], Light.prototype, "_shadowEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("excludeWithLayerMask")
], Light.prototype, "_excludeWithLayerMask", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("includeOnlyWithLayerMask")
], Light.prototype, "_includeOnlyWithLayerMask", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])("lightmapMode")
], Light.prototype, "_lightmapMode", void 0);
return Light;
}(_node__WEBPACK_IMPORTED_MODULE_4__["Node"]));
/***/ }),
/***/ "./Lights/pointLight.ts":
/*!******************************!*\
!*** ./Lights/pointLight.ts ***!
\******************************/
/*! exports provided: PointLight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PointLight", function() { return PointLight; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts");
/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_0", function (name, scene) {
return function () { return new PointLight(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), scene); };
});
/**
* A point light is a light defined by an unique point in world space.
* The light is emitted in every direction from this point.
* A good example of a point light is a standard light bulb.
* Documentation: https://doc.babylonjs.com/babylon101/lights
*/
var PointLight = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PointLight, _super);
/**
* Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
* A PointLight emits the light in every direction.
* It can cast shadows.
* If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
* ```javascript
* var pointLight = new PointLight("pl", camera.position, scene);
* ```
* Documentation : https://doc.babylonjs.com/babylon101/lights
* @param name The light friendly name
* @param position The position of the point light in the scene
* @param scene The scene the lights belongs to
*/
function PointLight(name, position, scene) {
var _this = _super.call(this, name, scene) || this;
_this._shadowAngle = Math.PI / 2;
_this.position = position;
return _this;
}
Object.defineProperty(PointLight.prototype, "shadowAngle", {
/**
* Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
* This specifies what angle the shadow will use to be created.
*
* It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
*/
get: function () {
return this._shadowAngle;
},
/**
* Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
* This specifies what angle the shadow will use to be created.
*
* It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
*/
set: function (value) {
this._shadowAngle = value;
this.forceProjectionMatrixCompute();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PointLight.prototype, "direction", {
/**
* Gets the direction if it has been set.
* In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
*/
get: function () {
return this._direction;
},
/**
* In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
*/
set: function (value) {
var previousNeedCube = this.needCube();
this._direction = value;
if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
this._shadowGenerator.recreateShadowMap();
}
},
enumerable: false,
configurable: true
});
/**
* Returns the string "PointLight"
* @returns the class name
*/
PointLight.prototype.getClassName = function () {
return "PointLight";
};
/**
* Returns the integer 0.
* @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
*/
PointLight.prototype.getTypeID = function () {
return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_POINTLIGHT;
};
/**
* Specifies wether or not the shadowmap should be a cube texture.
* @returns true if the shadowmap needs to be a cube texture.
*/
PointLight.prototype.needCube = function () {
return !this.direction;
};
/**
* Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
* @param faceIndex The index of the face we are computed the direction to generate shadow
* @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
*/
PointLight.prototype.getShadowDirection = function (faceIndex) {
if (this.direction) {
return _super.prototype.getShadowDirection.call(this, faceIndex);
}
else {
switch (faceIndex) {
case 0:
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](1.0, 0.0, 0.0);
case 1:
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](-1.0, 0.0, 0.0);
case 2:
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, -1.0, 0.0);
case 3:
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 1.0, 0.0);
case 4:
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 0.0, 1.0);
case 5:
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"](0.0, 0.0, -1.0);
}
}
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
};
/**
* Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
* - fov = PI / 2
* - aspect ratio : 1.0
* - z-near and far equal to the active camera minZ and maxZ.
* Returns the PointLight.
*/
PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
};
PointLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 4);
this._uniformBuffer.addUniform("vLightFalloff", 4);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
/**
* Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
* @param effect The effect to update
* @param lightIndex The index of the light in the effect to update
* @returns The point light
*/
PointLight.prototype.transferToEffect = function (effect, lightIndex) {
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
}
else {
this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
}
this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
return this;
};
PointLight.prototype.transferToNodeMaterialEffect = function (effect, lightDataUniformName) {
if (this.computeTransformedInformation()) {
effect.setFloat3(lightDataUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z);
}
else {
effect.setFloat3(lightDataUniformName, this.position.x, this.position.y, this.position.z);
}
return this;
};
/**
* Prepares the list of defines specific to the light type.
* @param defines the list of defines
* @param lightIndex defines the index of the light for the effect
*/
PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
defines["POINTLIGHT" + lightIndex] = true;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PointLight.prototype, "shadowAngle", null);
return PointLight;
}(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"]));
/***/ }),
/***/ "./Lights/shadowLight.ts":
/*!*******************************!*\
!*** ./Lights/shadowLight.ts ***!
\*******************************/
/*! exports provided: ShadowLight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ShadowLight", function() { return ShadowLight; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./light */ "./Lights/light.ts");
/* harmony import */ var _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Maths/math.axis */ "./Maths/math.axis.ts");
/**
* Base implementation IShadowLight
* It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
*/
var ShadowLight = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ShadowLight, _super);
function ShadowLight() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this._needProjectionMatrixCompute = true;
return _this;
}
ShadowLight.prototype._setPosition = function (value) {
this._position = value;
};
Object.defineProperty(ShadowLight.prototype, "position", {
/**
* Sets the position the shadow will be casted from. Also use as the light position for both
* point and spot lights.
*/
get: function () {
return this._position;
},
/**
* Sets the position the shadow will be casted from. Also use as the light position for both
* point and spot lights.
*/
set: function (value) {
this._setPosition(value);
},
enumerable: false,
configurable: true
});
ShadowLight.prototype._setDirection = function (value) {
this._direction = value;
};
Object.defineProperty(ShadowLight.prototype, "direction", {
/**
* In 2d mode (needCube being false), gets the direction used to cast the shadow.
* Also use as the light direction on spot and directional lights.
*/
get: function () {
return this._direction;
},
/**
* In 2d mode (needCube being false), sets the direction used to cast the shadow.
* Also use as the light direction on spot and directional lights.
*/
set: function (value) {
this._setDirection(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
/**
* Gets the shadow projection clipping minimum z value.
*/
get: function () {
return this._shadowMinZ;
},
/**
* Sets the shadow projection clipping minimum z value.
*/
set: function (value) {
this._shadowMinZ = value;
this.forceProjectionMatrixCompute();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
/**
* Sets the shadow projection clipping maximum z value.
*/
get: function () {
return this._shadowMaxZ;
},
/**
* Gets the shadow projection clipping maximum z value.
*/
set: function (value) {
this._shadowMaxZ = value;
this.forceProjectionMatrixCompute();
},
enumerable: false,
configurable: true
});
/**
* Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
* @returns true if the information has been computed, false if it does not need to (no parenting)
*/
ShadowLight.prototype.computeTransformedInformation = function () {
if (this.parent && this.parent.getWorldMatrix) {
if (!this.transformedPosition) {
this.transformedPosition = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
// In case the direction is present.
if (this.direction) {
if (!this.transformedDirection) {
this.transformedDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
}
return true;
}
return false;
};
/**
* Return the depth scale used for the shadow map.
* @returns the depth scale.
*/
ShadowLight.prototype.getDepthScale = function () {
return 50.0;
};
/**
* Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
* @param faceIndex The index of the face we are computed the direction to generate shadow
* @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
*/
ShadowLight.prototype.getShadowDirection = function (faceIndex) {
return this.transformedDirection ? this.transformedDirection : this.direction;
};
/**
* Returns the ShadowLight absolute position in the World.
* @returns the position vector in world space
*/
ShadowLight.prototype.getAbsolutePosition = function () {
return this.transformedPosition ? this.transformedPosition : this.position;
};
/**
* Sets the ShadowLight direction toward the passed target.
* @param target The point to target in local space
* @returns the updated ShadowLight direction
*/
ShadowLight.prototype.setDirectionToTarget = function (target) {
this.direction = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(target.subtract(this.position));
return this.direction;
};
/**
* Returns the light rotation in euler definition.
* @returns the x y z rotation in local space.
*/
ShadowLight.prototype.getRotation = function () {
this.direction.normalize();
var xaxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(this.direction, _Maths_math_axis__WEBPACK_IMPORTED_MODULE_4__["Axis"].Y);
var yaxis = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Cross(xaxis, this.direction);
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].RotationFromAxis(xaxis, yaxis, this.direction);
};
/**
* Returns whether or not the shadow generation require a cube texture or a 2d texture.
* @returns true if a cube texture needs to be use
*/
ShadowLight.prototype.needCube = function () {
return false;
};
/**
* Detects if the projection matrix requires to be recomputed this frame.
* @returns true if it requires to be recomputed otherwise, false.
*/
ShadowLight.prototype.needProjectionMatrixCompute = function () {
return this._needProjectionMatrixCompute;
};
/**
* Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
*/
ShadowLight.prototype.forceProjectionMatrixCompute = function () {
this._needProjectionMatrixCompute = true;
};
/** @hidden */
ShadowLight.prototype._initCache = function () {
_super.prototype._initCache.call(this);
this._cache.position = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
};
/** @hidden */
ShadowLight.prototype._isSynchronized = function () {
if (!this._cache.position.equals(this.position)) {
return false;
}
return true;
};
/**
* Computes the world matrix of the node
* @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
* @returns the world matrix
*/
ShadowLight.prototype.computeWorldMatrix = function (force) {
if (!force && this.isSynchronized()) {
this._currentRenderId = this.getScene().getRenderId();
return this._worldMatrix;
}
this._updateCache();
this._cache.position.copyFrom(this.position);
if (!this._worldMatrix) {
this._worldMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Identity();
}
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
if (this.parent && this.parent.getWorldMatrix) {
this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
this._markSyncedWithParent();
}
// Cache the determinant
this._worldMatrixDeterminantIsDirty = true;
return this._worldMatrix;
};
/**
* Gets the minZ used for shadow according to both the scene and the light.
* @param activeCamera The camera we are returning the min for
* @returns the depth min z
*/
ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
};
/**
* Gets the maxZ used for shadow according to both the scene and the light.
* @param activeCamera The camera we are returning the max for
* @returns the depth max z
*/
ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
};
/**
* Sets the shadow projection matrix in parameter to the generated projection matrix.
* @param matrix The materix to updated with the projection information
* @param viewMatrix The transform matrix of the light
* @param renderList The list of mesh to render in the map
* @returns The current light
*/
ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
if (this.customProjectionMatrixBuilder) {
this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
}
else {
this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
}
return this;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], ShadowLight.prototype, "position", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], ShadowLight.prototype, "direction", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ShadowLight.prototype, "shadowMinZ", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], ShadowLight.prototype, "shadowMaxZ", null);
return ShadowLight;
}(_light__WEBPACK_IMPORTED_MODULE_3__["Light"]));
/***/ }),
/***/ "./Lights/spotLight.ts":
/*!*****************************!*\
!*** ./Lights/spotLight.ts ***!
\*****************************/
/*! exports provided: SpotLight */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SpotLight", function() { return SpotLight; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _node__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../node */ "./node.ts");
/* harmony import */ var _light__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./light */ "./Lights/light.ts");
/* harmony import */ var _shadowLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./shadowLight */ "./Lights/shadowLight.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
_node__WEBPACK_IMPORTED_MODULE_3__["Node"].AddNodeConstructor("Light_Type_2", function (name, scene) {
return function () { return new SpotLight(name, _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero(), 0, 0, scene); };
});
/**
* A spot light is defined by a position, a direction, an angle, and an exponent.
* These values define a cone of light starting from the position, emitting toward the direction.
* The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
* and the exponent defines the speed of the decay of the light with distance (reach).
* Documentation: https://doc.babylonjs.com/babylon101/lights
*/
var SpotLight = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SpotLight, _super);
/**
* Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
* It can cast shadows.
* Documentation : https://doc.babylonjs.com/babylon101/lights
* @param name The light friendly name
* @param position The position of the spot light in the scene
* @param direction The direction of the light in the scene
* @param angle The cone angle of the light in Radians
* @param exponent The light decay speed with the distance from the emission spot
* @param scene The scene the lights belongs to
*/
function SpotLight(name, position, direction, angle, exponent, scene) {
var _this = _super.call(this, name, scene) || this;
_this._innerAngle = 0;
_this._projectionTextureMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero();
_this._projectionTextureLightNear = 1e-6;
_this._projectionTextureLightFar = 1000.0;
_this._projectionTextureUpDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Up();
_this._projectionTextureViewLightDirty = true;
_this._projectionTextureProjectionLightDirty = true;
_this._projectionTextureDirty = true;
_this._projectionTextureViewTargetVector = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Zero();
_this._projectionTextureViewLightMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero();
_this._projectionTextureProjectionLightMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].Zero();
_this._projectionTextureScalingMatrix = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValues(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);
_this.position = position;
_this.direction = direction;
_this.angle = angle;
_this.exponent = exponent;
return _this;
}
Object.defineProperty(SpotLight.prototype, "angle", {
/**
* Gets the cone angle of the spot light in Radians.
*/
get: function () {
return this._angle;
},
/**
* Sets the cone angle of the spot light in Radians.
*/
set: function (value) {
this._angle = value;
this._cosHalfAngle = Math.cos(value * 0.5);
this._projectionTextureProjectionLightDirty = true;
this.forceProjectionMatrixCompute();
this._computeAngleValues();
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "innerAngle", {
/**
* Only used in gltf falloff mode, this defines the angle where
* the directional falloff will start before cutting at angle which could be seen
* as outer angle.
*/
get: function () {
return this._innerAngle;
},
/**
* Only used in gltf falloff mode, this defines the angle where
* the directional falloff will start before cutting at angle which could be seen
* as outer angle.
*/
set: function (value) {
this._innerAngle = value;
this._computeAngleValues();
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
/**
* Allows scaling the angle of the light for shadow generation only.
*/
get: function () {
return this._shadowAngleScale;
},
/**
* Allows scaling the angle of the light for shadow generation only.
*/
set: function (value) {
this._shadowAngleScale = value;
this.forceProjectionMatrixCompute();
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
/**
* Allows reading the projecton texture
*/
get: function () {
return this._projectionTextureMatrix;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
/**
* Gets the near clip of the Spotlight for texture projection.
*/
get: function () {
return this._projectionTextureLightNear;
},
/**
* Sets the near clip of the Spotlight for texture projection.
*/
set: function (value) {
this._projectionTextureLightNear = value;
this._projectionTextureProjectionLightDirty = true;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
/**
* Gets the far clip of the Spotlight for texture projection.
*/
get: function () {
return this._projectionTextureLightFar;
},
/**
* Sets the far clip of the Spotlight for texture projection.
*/
set: function (value) {
this._projectionTextureLightFar = value;
this._projectionTextureProjectionLightDirty = true;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
/**
* Gets the Up vector of the Spotlight for texture projection.
*/
get: function () {
return this._projectionTextureUpDirection;
},
/**
* Sets the Up vector of the Spotlight for texture projection.
*/
set: function (value) {
this._projectionTextureUpDirection = value;
this._projectionTextureProjectionLightDirty = true;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SpotLight.prototype, "projectionTexture", {
/**
* Gets the projection texture of the light.
*/
get: function () {
return this._projectionTexture;
},
/**
* Sets the projection texture of the light.
*/
set: function (value) {
var _this = this;
if (this._projectionTexture === value) {
return;
}
this._projectionTexture = value;
this._projectionTextureDirty = true;
if (this._projectionTexture && !this._projectionTexture.isReady()) {
var texture = this._projectionTexture;
if (texture.onLoadObservable) {
texture.onLoadObservable.addOnce(function () {
_this._markMeshesAsLightDirty();
});
}
}
},
enumerable: false,
configurable: true
});
/**
* Returns the string "SpotLight".
* @returns the class name
*/
SpotLight.prototype.getClassName = function () {
return "SpotLight";
};
/**
* Returns the integer 2.
* @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
*/
SpotLight.prototype.getTypeID = function () {
return _light__WEBPACK_IMPORTED_MODULE_4__["Light"].LIGHTTYPEID_SPOTLIGHT;
};
/**
* Overrides the direction setter to recompute the projection texture view light Matrix.
*/
SpotLight.prototype._setDirection = function (value) {
_super.prototype._setDirection.call(this, value);
this._projectionTextureViewLightDirty = true;
};
/**
* Overrides the position setter to recompute the projection texture view light Matrix.
*/
SpotLight.prototype._setPosition = function (value) {
_super.prototype._setPosition.call(this, value);
this._projectionTextureViewLightDirty = true;
};
/**
* Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
* Returns the SpotLight.
*/
SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
var activeCamera = this.getScene().activeCamera;
if (!activeCamera) {
return;
}
this._shadowAngleScale = this._shadowAngleScale || 1;
var angle = this._shadowAngleScale * this._angle;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
};
SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
this._projectionTextureViewLightDirty = false;
this._projectionTextureDirty = true;
this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
};
SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
this._projectionTextureProjectionLightDirty = false;
this._projectionTextureDirty = true;
var light_far = this.projectionTextureLightFar;
var light_near = this.projectionTextureLightNear;
var P = light_far / (light_far - light_near);
var Q = -P * light_near;
var S = 1.0 / Math.tan(this._angle / 2.0);
var A = 1.0;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValuesToRef(S / A, 0.0, 0.0, 0.0, 0.0, S, 0.0, 0.0, 0.0, 0.0, P, 1.0, 0.0, 0.0, Q, 0.0, this._projectionTextureProjectionLightMatrix);
};
/**
* Main function for light texture projection matrix computing.
*/
SpotLight.prototype._computeProjectionTextureMatrix = function () {
this._projectionTextureDirty = false;
this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
if (this._projectionTexture instanceof _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"]) {
var u = this._projectionTexture.uScale / 2.0;
var v = this._projectionTexture.vScale / 2.0;
_Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Matrix"].FromValuesToRef(u, 0.0, 0.0, 0.0, 0.0, v, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0, this._projectionTextureScalingMatrix);
}
this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
};
SpotLight.prototype._buildUniformLayout = function () {
this._uniformBuffer.addUniform("vLightData", 4);
this._uniformBuffer.addUniform("vLightDiffuse", 4);
this._uniformBuffer.addUniform("vLightSpecular", 4);
this._uniformBuffer.addUniform("vLightDirection", 3);
this._uniformBuffer.addUniform("vLightFalloff", 4);
this._uniformBuffer.addUniform("shadowsInfo", 3);
this._uniformBuffer.addUniform("depthValues", 2);
this._uniformBuffer.create();
};
SpotLight.prototype._computeAngleValues = function () {
this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
};
/**
* Sets the passed Effect "effect" with the Light textures.
* @param effect The effect to update
* @param lightIndex The index of the light in the effect to update
* @returns The light
*/
SpotLight.prototype.transferTexturesToEffect = function (effect, lightIndex) {
if (this.projectionTexture && this.projectionTexture.isReady()) {
if (this._projectionTextureViewLightDirty) {
this._computeProjectionTextureViewLightMatrix();
}
if (this._projectionTextureProjectionLightDirty) {
this._computeProjectionTextureProjectionLightMatrix();
}
if (this._projectionTextureDirty) {
this._computeProjectionTextureMatrix();
}
effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
}
return this;
};
/**
* Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
* @param effect The effect to update
* @param lightIndex The index of the light in the effect to update
* @returns The spot light
*/
SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
var normalizeDirection;
if (this.computeTransformedInformation()) {
this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
normalizeDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.transformedDirection);
}
else {
this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
normalizeDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction);
}
this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
return this;
};
SpotLight.prototype.transferToNodeMaterialEffect = function (effect, lightDataUniformName) {
var normalizeDirection;
if (this.computeTransformedInformation()) {
normalizeDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.transformedDirection);
}
else {
normalizeDirection = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].Normalize(this.direction);
}
if (this.getScene().useRightHandedSystem) {
effect.setFloat3(lightDataUniformName, -normalizeDirection.x, -normalizeDirection.y, -normalizeDirection.z);
}
else {
effect.setFloat3(lightDataUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z);
}
return this;
};
/**
* Disposes the light and the associated resources.
*/
SpotLight.prototype.dispose = function () {
_super.prototype.dispose.call(this);
if (this._projectionTexture) {
this._projectionTexture.dispose();
}
};
/**
* Prepares the list of defines specific to the light type.
* @param defines the list of defines
* @param lightIndex defines the index of the light for the effect
*/
SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
defines["SPOTLIGHT" + lightIndex] = true;
defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture && this.projectionTexture.isReady() ? true : false;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "angle", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "innerAngle", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "shadowAngleScale", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "exponent", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "projectionTextureLightNear", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "projectionTextureLightFar", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], SpotLight.prototype, "projectionTextureUpDirection", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])("projectedLightTexture")
], SpotLight.prototype, "_projectionTexture", void 0);
return SpotLight;
}(_shadowLight__WEBPACK_IMPORTED_MODULE_5__["ShadowLight"]));
/***/ }),
/***/ "./Loading/Plugins/babylonFileLoader.ts":
/*!**********************************************!*\
!*** ./Loading/Plugins/babylonFileLoader.ts ***!
\**********************************************/
/*! exports provided: _BabylonLoaderRegistered, BabylonFileLoaderConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _BabylonLoaderRegistered; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BabylonFileLoaderConfiguration", function() { return BabylonFileLoaderConfiguration; });
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Cameras/camera */ "./Cameras/camera.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Meshes/mesh */ "./Meshes/mesh.ts");
/* harmony import */ var _Meshes_geometry__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Meshes/geometry */ "./Meshes/geometry.ts");
/* harmony import */ var _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Meshes/transformNode */ "./Meshes/transformNode.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Materials/multiMaterial */ "./Materials/multiMaterial.ts");
/* harmony import */ var _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Materials/Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts");
/* harmony import */ var _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Materials/Textures/hdrCubeTexture */ "./Materials/Textures/hdrCubeTexture.ts");
/* harmony import */ var _Animations_animationGroup__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Animations/animationGroup */ "./Animations/animationGroup.ts");
/* harmony import */ var _Lights_light__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Lights/light */ "./Lights/light.ts");
/* harmony import */ var _sceneComponent__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../sceneComponent */ "./sceneComponent.ts");
/* harmony import */ var _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Loading/sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony import */ var _abstractScene__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../abstractScene */ "./abstractScene.ts");
/* harmony import */ var _assetContainer__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../assetContainer */ "./assetContainer.ts");
/* harmony import */ var _Actions_actionManager__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Actions/actionManager */ "./Actions/actionManager.ts");
/* harmony import */ var _Bones_skeleton__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Bones/skeleton */ "./Bones/skeleton.ts");
/* harmony import */ var _Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../Morph/morphTargetManager */ "./Morph/morphTargetManager.ts");
/* harmony import */ var _Physics_Plugins_cannonJSPlugin__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Physics/Plugins/cannonJSPlugin */ "./Physics/Plugins/cannonJSPlugin.ts");
/* harmony import */ var _Physics_Plugins_oimoJSPlugin__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../Physics/Plugins/oimoJSPlugin */ "./Physics/Plugins/oimoJSPlugin.ts");
/* harmony import */ var _Physics_Plugins_ammoJSPlugin__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Physics/Plugins/ammoJSPlugin */ "./Physics/Plugins/ammoJSPlugin.ts");
/* harmony import */ var _Probes_reflectionProbe__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Probes/reflectionProbe */ "./Probes/reflectionProbe.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../Misc/stringTools */ "./Misc/stringTools.ts");
/* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts");
/** @hidden */
var _BabylonLoaderRegistered = true;
/**
* Helps setting up some configuration for the babylon file loader.
*/
var BabylonFileLoaderConfiguration = /** @class */ (function () {
function BabylonFileLoaderConfiguration() {
}
/**
* The loader does not allow injecting custom physix engine into the plugins.
* Unfortunately in ES6, we need to manually inject them into the plugin.
* So you could set this variable to your engine import to make it work.
*/
BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine = undefined;
return BabylonFileLoaderConfiguration;
}());
var parseMaterialById = function (id, parsedData, scene, rootUrl) {
for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
var parsedMaterial = parsedData.materials[index];
if (parsedMaterial.id === id) {
return _Materials_material__WEBPACK_IMPORTED_MODULE_7__["Material"].Parse(parsedMaterial, scene, rootUrl);
}
}
return null;
};
var isDescendantOf = function (mesh, names, hierarchyIds) {
for (var i in names) {
if (mesh.name === names[i]) {
hierarchyIds.push(mesh.id);
return true;
}
}
if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
hierarchyIds.push(mesh.id);
return true;
}
return false;
};
var logOperation = function (operation, producer) {
return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
};
var loadDetailLevels = function (scene, mesh) {
var mastermesh = mesh;
// Every value specified in the ids array of the lod data points to another mesh which should be used as the lower LOD level.
// The distances (or coverages) array values specified are used along with the lod mesh ids as a hint to determine the switching threshold for the various LODs.
if (mesh._waitingData.lods) {
if (mesh._waitingData.lods.ids && mesh._waitingData.lods.ids.length > 0) {
var lodmeshes = mesh._waitingData.lods.ids;
var wasenabled = mastermesh.isEnabled(false);
if (mesh._waitingData.lods.distances) {
var distances = mesh._waitingData.lods.distances;
if (distances.length >= lodmeshes.length) {
var culling = (distances.length > lodmeshes.length) ? distances[distances.length - 1] : 0;
mastermesh.setEnabled(false);
for (var index = 0; index < lodmeshes.length; index++) {
var lodid = lodmeshes[index];
var lodmesh = scene.getMeshByID(lodid);
if (lodmesh != null) {
mastermesh.addLODLevel(distances[index], lodmesh);
}
}
if (culling > 0) {
mastermesh.addLODLevel(culling, null);
}
if (wasenabled === true) {
mastermesh.setEnabled(true);
}
}
else {
_Misc_tools__WEBPACK_IMPORTED_MODULE_25__["Tools"].Warn("Invalid level of detail distances for " + mesh.name);
}
}
}
mesh._waitingData.lods = null;
}
};
var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
if (addToScene === void 0) { addToScene = false; }
var container = new _assetContainer__WEBPACK_IMPORTED_MODULE_16__["AssetContainer"](scene);
// Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
// when SceneLoader.debugLogging = true (default), or exception encountered.
// Everything stored in var log instead of writing separate lines to support only writing in exception,
// and avoid problems with multiple concurrent .babylon loads.
var log = "importScene has failed JSON parse";
try {
var parsedData = JSON.parse(data);
log = "";
var fullDetails = _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel === _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].DETAILED_LOGGING;
var index;
var cache;
// Environment texture
if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
// PBR needed for both HDR texture (gamma space) & a sky box
var isPBR = parsedData.isPBR !== undefined ? parsedData.isPBR : true;
if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
var hdrTexture = new _Materials_Textures_hdrCubeTexture__WEBPACK_IMPORTED_MODULE_10__["HDRCubeTexture"]((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene, hdrSize, true, !isPBR);
if (parsedData.environmentTextureRotationY) {
hdrTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = hdrTexture;
}
else {
if (_Misc_stringTools__WEBPACK_IMPORTED_MODULE_26__["StringTools"].EndsWith(parsedData.environmentTexture, ".env")) {
var compressedTexture = new _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__["CubeTexture"]((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene);
if (parsedData.environmentTextureRotationY) {
compressedTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = compressedTexture;
}
else {
var cubeTexture = _Materials_Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__["CubeTexture"].CreateFromPrefilteredData((parsedData.environmentTexture.match(/https?:\/\//g) ? "" : rootUrl) + parsedData.environmentTexture, scene);
if (parsedData.environmentTextureRotationY) {
cubeTexture.rotationY = parsedData.environmentTextureRotationY;
}
scene.environmentTexture = cubeTexture;
}
}
if (parsedData.createDefaultSkybox === true) {
var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
scene.createDefaultSkybox(scene.environmentTexture, isPBR, skyboxScale, skyboxBlurLevel);
}
container.environmentTexture = scene.environmentTexture;
}
// Environment Intensity
if (parsedData.environmentIntensity !== undefined && parsedData.environmentIntensity !== null) {
scene.environmentIntensity = parsedData.environmentIntensity;
}
// Lights
if (parsedData.lights !== undefined && parsedData.lights !== null) {
for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
var parsedLight = parsedData.lights[index];
var light = _Lights_light__WEBPACK_IMPORTED_MODULE_12__["Light"].Parse(parsedLight, scene);
if (light) {
container.lights.push(light);
log += (index === 0 ? "\n\tLights:" : "");
log += "\n\t\t" + light.toString(fullDetails);
}
}
}
// Reflection probes
if (parsedData.reflectionProbes !== undefined && parsedData.reflectionProbes !== null) {
for (index = 0, cache = parsedData.reflectionProbes.length; index < cache; index++) {
var parsedReflectionProbe = parsedData.reflectionProbes[index];
var reflectionProbe = _Probes_reflectionProbe__WEBPACK_IMPORTED_MODULE_23__["ReflectionProbe"].Parse(parsedReflectionProbe, scene, rootUrl);
if (reflectionProbe) {
container.reflectionProbes.push(reflectionProbe);
log += (index === 0 ? "\n\tReflection Probes:" : "");
log += "\n\t\t" + reflectionProbe.toString(fullDetails);
}
}
}
// Animations
if (parsedData.animations !== undefined && parsedData.animations !== null) {
for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
var parsedAnimation = parsedData.animations[index];
var internalClass = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_24__["_TypeStore"].GetClass("BABYLON.Animation");
if (internalClass) {
var animation = internalClass.Parse(parsedAnimation);
scene.animations.push(animation);
container.animations.push(animation);
log += (index === 0 ? "\n\tAnimations:" : "");
log += "\n\t\t" + animation.toString(fullDetails);
}
}
}
// Materials
if (parsedData.materials !== undefined && parsedData.materials !== null) {
for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
var parsedMaterial = parsedData.materials[index];
var mat = _Materials_material__WEBPACK_IMPORTED_MODULE_7__["Material"].Parse(parsedMaterial, scene, rootUrl);
if (mat) {
container.materials.push(mat);
log += (index === 0 ? "\n\tMaterials:" : "");
log += "\n\t\t" + mat.toString(fullDetails);
// Textures
var textures = mat.getActiveTextures();
textures.forEach(function (t) {
if (container.textures.indexOf(t) == -1) {
container.textures.push(t);
}
});
}
}
}
if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
var parsedMultiMaterial = parsedData.multiMaterials[index];
var mmat = _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_8__["MultiMaterial"].ParseMultiMaterial(parsedMultiMaterial, scene);
container.multiMaterials.push(mmat);
log += (index === 0 ? "\n\tMultiMaterials:" : "");
log += "\n\t\t" + mmat.toString(fullDetails);
// Textures
var textures = mmat.getActiveTextures();
textures.forEach(function (t) {
if (container.textures.indexOf(t) == -1) {
container.textures.push(t);
}
});
}
}
// Morph targets
if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
var managerData = _a[_i];
container.morphTargetManagers.push(_Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_19__["MorphTargetManager"].Parse(managerData, scene));
}
}
// Skeletons
if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
var parsedSkeleton = parsedData.skeletons[index];
var skeleton = _Bones_skeleton__WEBPACK_IMPORTED_MODULE_18__["Skeleton"].Parse(parsedSkeleton, scene);
container.skeletons.push(skeleton);
log += (index === 0 ? "\n\tSkeletons:" : "");
log += "\n\t\t" + skeleton.toString(fullDetails);
}
}
// Geometries
var geometries = parsedData.geometries;
if (geometries !== undefined && geometries !== null) {
var addedGeometry = new Array();
// VertexData
var vertexData = geometries.vertexData;
if (vertexData !== undefined && vertexData !== null) {
for (index = 0, cache = vertexData.length; index < cache; index++) {
var parsedVertexData = vertexData[index];
addedGeometry.push(_Meshes_geometry__WEBPACK_IMPORTED_MODULE_5__["Geometry"].Parse(parsedVertexData, scene, rootUrl));
}
}
addedGeometry.forEach(function (g) {
if (g) {
container.geometries.push(g);
}
});
}
// Transform nodes
if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
var parsedTransformNode = parsedData.transformNodes[index];
var node = _Meshes_transformNode__WEBPACK_IMPORTED_MODULE_6__["TransformNode"].Parse(parsedTransformNode, scene, rootUrl);
container.transformNodes.push(node);
}
}
// Meshes
if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
var parsedMesh = parsedData.meshes[index];
var mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].Parse(parsedMesh, scene, rootUrl);
container.meshes.push(mesh);
log += (index === 0 ? "\n\tMeshes:" : "");
log += "\n\t\t" + mesh.toString(fullDetails);
}
}
// Cameras
if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
var parsedCamera = parsedData.cameras[index];
var camera = _Cameras_camera__WEBPACK_IMPORTED_MODULE_1__["Camera"].Parse(parsedCamera, scene);
container.cameras.push(camera);
log += (index === 0 ? "\n\tCameras:" : "");
log += "\n\t\t" + camera.toString(fullDetails);
}
}
// Postprocesses
if (parsedData.postProcesses !== undefined && parsedData.postProcesses !== null) {
for (index = 0, cache = parsedData.postProcesses.length; index < cache; index++) {
var parsedPostProcess = parsedData.postProcesses[index];
var postProcess = _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_27__["PostProcess"].Parse(parsedPostProcess, scene, rootUrl);
if (postProcess) {
container.postProcesses.push(postProcess);
log += (index === 0 ? "\n\Postprocesses:" : "");
log += "\n\t\t" + postProcess.toString();
}
}
}
// Animation Groups
if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
var parsedAnimationGroup = parsedData.animationGroups[index];
var animationGroup = _Animations_animationGroup__WEBPACK_IMPORTED_MODULE_11__["AnimationGroup"].Parse(parsedAnimationGroup, scene);
container.animationGroups.push(animationGroup);
log += (index === 0 ? "\n\tAnimationGroups:" : "");
log += "\n\t\t" + animationGroup.toString(fullDetails);
}
}
// Browsing all the graph to connect the dots
for (index = 0, cache = scene.cameras.length; index < cache; index++) {
var camera = scene.cameras[index];
if (camera._waitingParentId) {
camera.parent = scene.getLastEntryByID(camera._waitingParentId);
camera._waitingParentId = null;
}
}
for (index = 0, cache = scene.lights.length; index < cache; index++) {
var light_1 = scene.lights[index];
if (light_1 && light_1._waitingParentId) {
light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
light_1._waitingParentId = null;
}
}
// Connect parents & children and parse actions and lods
for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
var transformNode = scene.transformNodes[index];
if (transformNode._waitingParentId) {
transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
transformNode._waitingParentId = null;
}
}
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
var mesh = scene.meshes[index];
if (mesh._waitingParentId) {
mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
mesh._waitingParentId = null;
}
if (mesh._waitingData.lods) {
loadDetailLevels(scene, mesh);
}
}
// link skeleton transform nodes
for (index = 0, cache = scene.skeletons.length; index < cache; index++) {
var skeleton = scene.skeletons[index];
if (skeleton._hasWaitingData) {
if (skeleton.bones != null) {
skeleton.bones.forEach(function (bone) {
if (bone._waitingTransformNodeId) {
var linkTransformNode = scene.getLastEntryByID(bone._waitingTransformNodeId);
if (linkTransformNode) {
bone.linkTransformNode(linkTransformNode);
}
bone._waitingTransformNodeId = null;
}
});
}
if (skeleton._waitingOverrideMeshId) {
skeleton.overrideMesh = scene.getMeshByID(skeleton._waitingOverrideMeshId);
skeleton._waitingOverrideMeshId = null;
}
skeleton._hasWaitingData = null;
}
}
// freeze world matrix application
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
var currentMesh = scene.meshes[index];
if (currentMesh._waitingData.freezeWorldMatrix) {
currentMesh.freezeWorldMatrix();
currentMesh._waitingData.freezeWorldMatrix = null;
}
else {
currentMesh.computeWorldMatrix(true);
}
}
// Lights exclusions / inclusions
for (index = 0, cache = scene.lights.length; index < cache; index++) {
var light_2 = scene.lights[index];
// Excluded check
if (light_2._excludedMeshesIds.length > 0) {
for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
if (excludedMesh) {
light_2.excludedMeshes.push(excludedMesh);
}
}
light_2._excludedMeshesIds = [];
}
// Included check
if (light_2._includedOnlyMeshesIds.length > 0) {
for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
if (includedOnlyMesh) {
light_2.includedOnlyMeshes.push(includedOnlyMesh);
}
}
light_2._includedOnlyMeshesIds = [];
}
}
_abstractScene__WEBPACK_IMPORTED_MODULE_15__["AbstractScene"].Parse(parsedData, scene, container, rootUrl);
// Actions (scene) Done last as it can access other objects.
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
var mesh = scene.meshes[index];
if (mesh._waitingData.actions) {
_Actions_actionManager__WEBPACK_IMPORTED_MODULE_17__["ActionManager"].Parse(mesh._waitingData.actions, mesh, scene);
mesh._waitingData.actions = null;
}
}
if (parsedData.actions !== undefined && parsedData.actions !== null) {
_Actions_actionManager__WEBPACK_IMPORTED_MODULE_17__["ActionManager"].Parse(parsedData.actions, null, scene);
}
}
catch (err) {
var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg);
throw err;
}
}
finally {
if (!addToScene) {
container.removeAllFromScene();
}
if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].NO_LOGGING) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].MINIMAL_LOGGING ? log : ""));
}
}
return container;
};
_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].RegisterPlugin({
name: "babylon.js",
extensions: ".babylon",
canDirectLoad: function (data) {
if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
return true;
}
return false;
},
importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
// Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
// when SceneLoader.debugLogging = true (default), or exception encountered.
// Everything stored in var log instead of writing separate lines to support only writing in exception,
// and avoid problems with multiple concurrent .babylon loads.
var log = "importMesh has failed JSON parse";
try {
var parsedData = JSON.parse(data);
log = "";
var fullDetails = _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel === _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].DETAILED_LOGGING;
if (!meshesNames) {
meshesNames = null;
}
else if (!Array.isArray(meshesNames)) {
meshesNames = [meshesNames];
}
var hierarchyIds = new Array();
if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
var loadedSkeletonsIds = [];
var loadedMaterialsIds = [];
var index;
var cache;
for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
var parsedMesh = parsedData.meshes[index];
if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
if (meshesNames !== null) {
// Remove found mesh name from list.
delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
}
//Geometry?
if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
//does the file contain geometries?
if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
//find the correct geometry and add it to the scene
var found = false;
["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
return;
}
else {
parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
if (parsedGeometryData.id === parsedMesh.geometryId) {
switch (geometryType) {
case "vertexData":
_Meshes_geometry__WEBPACK_IMPORTED_MODULE_5__["Geometry"].Parse(parsedGeometryData, scene, rootUrl);
break;
}
found = true;
}
});
}
});
if (found === false) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Geometry not found for mesh " + parsedMesh.id);
}
}
}
// Material ?
if (parsedMesh.materialId) {
var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
if (parsedMultiMaterial.id === parsedMesh.materialId) {
for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
var subMatId = parsedMultiMaterial.materials[matIndex];
loadedMaterialsIds.push(subMatId);
var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
if (mat) {
log += "\n\tMaterial " + mat.toString(fullDetails);
}
}
loadedMaterialsIds.push(parsedMultiMaterial.id);
var mmat = _Materials_multiMaterial__WEBPACK_IMPORTED_MODULE_8__["MultiMaterial"].ParseMultiMaterial(parsedMultiMaterial, scene);
if (mmat) {
materialFound = true;
log += "\n\tMulti-Material " + mmat.toString(fullDetails);
}
break;
}
}
}
if (materialFound === false) {
loadedMaterialsIds.push(parsedMesh.materialId);
var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
if (!mat) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn("Material not found for mesh " + parsedMesh.id);
}
else {
log += "\n\tMaterial " + mat.toString(fullDetails);
}
}
}
// Skeleton ?
if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
if (skeletonAlreadyLoaded === false) {
for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
var parsedSkeleton = parsedData.skeletons[skeletonIndex];
if (parsedSkeleton.id === parsedMesh.skeletonId) {
var skeleton = _Bones_skeleton__WEBPACK_IMPORTED_MODULE_18__["Skeleton"].Parse(parsedSkeleton, scene);
skeletons.push(skeleton);
loadedSkeletonsIds.push(parsedSkeleton.id);
log += "\n\tSkeleton " + skeleton.toString(fullDetails);
}
}
}
}
// Morph targets ?
if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
var managerData = _a[_i];
_Morph_morphTargetManager__WEBPACK_IMPORTED_MODULE_19__["MorphTargetManager"].Parse(managerData, scene);
}
}
var mesh = _Meshes_mesh__WEBPACK_IMPORTED_MODULE_4__["Mesh"].Parse(parsedMesh, scene, rootUrl);
meshes.push(mesh);
log += "\n\tMesh " + mesh.toString(fullDetails);
}
}
// Connecting parents and lods
var currentMesh;
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
currentMesh = scene.meshes[index];
if (currentMesh._waitingParentId) {
currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
currentMesh._waitingParentId = null;
}
if (currentMesh._waitingData.lods) {
loadDetailLevels(scene, currentMesh);
}
}
// link skeleton transform nodes
for (index = 0, cache = scene.skeletons.length; index < cache; index++) {
var skeleton = scene.skeletons[index];
if (skeleton._hasWaitingData) {
if (skeleton.bones != null) {
skeleton.bones.forEach(function (bone) {
if (bone._waitingTransformNodeId) {
var linkTransformNode = scene.getLastEntryByID(bone._waitingTransformNodeId);
if (linkTransformNode) {
bone.linkTransformNode(linkTransformNode);
}
bone._waitingTransformNodeId = null;
}
});
}
if (skeleton._waitingOverrideMeshId) {
skeleton.overrideMesh = scene.getMeshByID(skeleton._waitingOverrideMeshId);
skeleton._waitingOverrideMeshId = null;
}
skeleton._hasWaitingData = null;
}
}
// freeze and compute world matrix application
for (index = 0, cache = scene.meshes.length; index < cache; index++) {
currentMesh = scene.meshes[index];
if (currentMesh._waitingData.freezeWorldMatrix) {
currentMesh.freezeWorldMatrix();
currentMesh._waitingData.freezeWorldMatrix = null;
}
else {
currentMesh.computeWorldMatrix(true);
}
}
}
// Particles
if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
var parser = _abstractScene__WEBPACK_IMPORTED_MODULE_15__["AbstractScene"].GetIndividualParser(_sceneComponent__WEBPACK_IMPORTED_MODULE_13__["SceneComponentConstants"].NAME_PARTICLESYSTEM);
if (parser) {
for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
var parsedParticleSystem = parsedData.particleSystems[index];
if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
}
}
}
}
return true;
}
catch (err) {
var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg);
throw err;
}
}
finally {
if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].NO_LOGGING) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].MINIMAL_LOGGING ? log : ""));
}
}
return false;
},
load: function (scene, data, rootUrl, onError) {
// Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
// when SceneLoader.debugLogging = true (default), or exception encountered.
// Everything stored in var log instead of writing separate lines to support only writing in exception,
// and avoid problems with multiple concurrent .babylon loads.
var log = "importScene has failed JSON parse";
try {
var parsedData = JSON.parse(data);
log = "";
// Scene
if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].ForceFullSceneLoadingForIncremental;
}
if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
scene.autoClear = parsedData.autoClear;
}
if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
scene.clearColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color4"].FromArray(parsedData.clearColor);
}
if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
scene.ambientColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].FromArray(parsedData.ambientColor);
}
if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
scene.gravity = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedData.gravity);
}
// Fog
if (parsedData.fogMode && parsedData.fogMode !== 0) {
scene.fogMode = parsedData.fogMode;
scene.fogColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].FromArray(parsedData.fogColor);
scene.fogStart = parsedData.fogStart;
scene.fogEnd = parsedData.fogEnd;
scene.fogDensity = parsedData.fogDensity;
log += "\tFog mode for scene: ";
switch (scene.fogMode) {
// getters not compiling, so using hardcoded
case 1:
log += "exp\n";
break;
case 2:
log += "exp2\n";
break;
case 3:
log += "linear\n";
break;
}
}
//Physics
if (parsedData.physicsEnabled) {
var physicsPlugin;
if (parsedData.physicsEngine === "cannon") {
physicsPlugin = new _Physics_Plugins_cannonJSPlugin__WEBPACK_IMPORTED_MODULE_20__["CannonJSPlugin"](undefined, undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);
}
else if (parsedData.physicsEngine === "oimo") {
physicsPlugin = new _Physics_Plugins_oimoJSPlugin__WEBPACK_IMPORTED_MODULE_21__["OimoJSPlugin"](undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine);
}
else if (parsedData.physicsEngine === "ammo") {
physicsPlugin = new _Physics_Plugins_ammoJSPlugin__WEBPACK_IMPORTED_MODULE_22__["AmmoJSPlugin"](undefined, BabylonFileLoaderConfiguration.LoaderInjectedPhysicsEngine, undefined);
}
log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
//else - default engine, which is currently oimo
var physicsGravity = parsedData.physicsGravity ? _Maths_math_vector__WEBPACK_IMPORTED_MODULE_2__["Vector3"].FromArray(parsedData.physicsGravity) : null;
scene.enablePhysics(physicsGravity, physicsPlugin);
}
// Metadata
if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
scene.metadata = parsedData.metadata;
}
//collisions, if defined. otherwise, default is true
if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
scene.collisionsEnabled = parsedData.collisionsEnabled;
}
var container = loadAssetContainer(scene, data, rootUrl, onError, true);
if (!container) {
return false;
}
if (parsedData.autoAnimate) {
scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
}
if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
scene.setActiveCameraByID(parsedData.activeCameraID);
}
// Finish
return true;
}
catch (err) {
var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
if (onError) {
onError(msg, err);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(msg);
throw err;
}
}
finally {
if (log !== null && _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].NO_LOGGING) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_0__["Logger"].Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (_Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].loggingLevel !== _Loading_sceneLoader__WEBPACK_IMPORTED_MODULE_14__["SceneLoader"].MINIMAL_LOGGING ? log : ""));
}
}
return false;
},
loadAssetContainer: function (scene, data, rootUrl, onError) {
var container = loadAssetContainer(scene, data, rootUrl, onError);
return container;
}
});
/***/ }),
/***/ "./Loading/Plugins/index.ts":
/*!**********************************!*\
!*** ./Loading/Plugins/index.ts ***!
\**********************************/
/*! exports provided: _BabylonLoaderRegistered, BabylonFileLoaderConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./babylonFileLoader */ "./Loading/Plugins/babylonFileLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__["_BabylonLoaderRegistered"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BabylonFileLoaderConfiguration", function() { return _babylonFileLoader__WEBPACK_IMPORTED_MODULE_0__["BabylonFileLoaderConfiguration"]; });
/***/ }),
/***/ "./Loading/index.ts":
/*!**************************!*\
!*** ./Loading/index.ts ***!
\**************************/
/*! exports provided: DefaultLoadingScreen, _BabylonLoaderRegistered, BabylonFileLoaderConfiguration, SceneLoaderAnimationGroupLoadingMode, SceneLoader, SceneLoaderFlags */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _loadingScreen__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./loadingScreen */ "./Loading/loadingScreen.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return _loadingScreen__WEBPACK_IMPORTED_MODULE_0__["DefaultLoadingScreen"]; });
/* harmony import */ var _Plugins_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Plugins/index */ "./Loading/Plugins/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BabylonLoaderRegistered", function() { return _Plugins_index__WEBPACK_IMPORTED_MODULE_1__["_BabylonLoaderRegistered"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BabylonFileLoaderConfiguration", function() { return _Plugins_index__WEBPACK_IMPORTED_MODULE_1__["BabylonFileLoaderConfiguration"]; });
/* harmony import */ var _sceneLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./sceneLoader */ "./Loading/sceneLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderAnimationGroupLoadingMode", function() { return _sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoaderAnimationGroupLoadingMode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return _sceneLoader__WEBPACK_IMPORTED_MODULE_2__["SceneLoader"]; });
/* harmony import */ var _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./sceneLoaderFlags */ "./Loading/sceneLoaderFlags.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_3__["SceneLoaderFlags"]; });
/***/ }),
/***/ "./Loading/loadingScreen.ts":
/*!**********************************!*\
!*** ./Loading/loadingScreen.ts ***!
\**********************************/
/*! exports provided: DefaultLoadingScreen */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultLoadingScreen", function() { return DefaultLoadingScreen; });
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/**
* Class used for the default loading screen
* @see https://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
*/
var DefaultLoadingScreen = /** @class */ (function () {
/**
* Creates a new default loading screen
* @param _renderingCanvas defines the canvas used to render the scene
* @param _loadingText defines the default text to display
* @param _loadingDivBackgroundColor defines the default background color
*/
function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
var _this = this;
if (_loadingText === void 0) { _loadingText = ""; }
if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
this._renderingCanvas = _renderingCanvas;
this._loadingText = _loadingText;
this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
// Resize
this._resizeLoadingUI = function () {
var canvasRect = _this._renderingCanvas.getBoundingClientRect();
var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
if (!_this._loadingDiv) {
return;
}
_this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
_this._loadingDiv.style.left = canvasRect.left + "px";
_this._loadingDiv.style.top = canvasRect.top + "px";
_this._loadingDiv.style.width = canvasRect.width + "px";
_this._loadingDiv.style.height = canvasRect.height + "px";
};
}
/**
* Function called to display the loading screen
*/
DefaultLoadingScreen.prototype.displayLoadingUI = function () {
if (this._loadingDiv) {
// Do not add a loading screen if there is already one
return;
}
this._loadingDiv = document.createElement("div");
this._loadingDiv.id = "babylonjsLoadingDiv";
this._loadingDiv.style.opacity = "0";
this._loadingDiv.style.transition = "opacity 1.5s ease";
this._loadingDiv.style.pointerEvents = "none";
// Loading text
this._loadingTextDiv = document.createElement("div");
this._loadingTextDiv.style.position = "absolute";
this._loadingTextDiv.style.left = "0";
this._loadingTextDiv.style.top = "50%";
this._loadingTextDiv.style.marginTop = "80px";
this._loadingTextDiv.style.width = "100%";
this._loadingTextDiv.style.height = "20px";
this._loadingTextDiv.style.fontFamily = "Arial";
this._loadingTextDiv.style.fontSize = "14px";
this._loadingTextDiv.style.color = "white";
this._loadingTextDiv.style.textAlign = "center";
this._loadingTextDiv.innerHTML = "Loading";
this._loadingDiv.appendChild(this._loadingTextDiv);
//set the predefined text
this._loadingTextDiv.innerHTML = this._loadingText;
// Generating keyframes
var style = document.createElement('style');
style.type = 'text/css';
var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
style.innerHTML = keyFrames;
document.getElementsByTagName('head')[0].appendChild(style);
var svgSupport = !!window.SVGSVGElement;
// Loading img
var imgBack = new Image();
if (!DefaultLoadingScreen.DefaultLogoUrl) {
imgBack.src = !svgSupport ? "https://cdn.babylonjs.com/Assets/babylonLogo.png" : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxODAuMTcgMjA4LjA0Ij48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2ZmZjt9LmNscy0ye2ZpbGw6I2UwNjg0Yjt9LmNscy0ze2ZpbGw6I2JiNDY0Yjt9LmNscy00e2ZpbGw6I2UwZGVkODt9LmNscy01e2ZpbGw6I2Q1ZDJjYTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPkJhYnlsb25Mb2dvPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iUGFnZV9FbGVtZW50cyIgZGF0YS1uYW1lPSJQYWdlIEVsZW1lbnRzIj48cGF0aCBjbGFzcz0iY2xzLTEiIGQ9Ik05MC4wOSwwLDAsNTJWMTU2bDkwLjA5LDUyLDkwLjA4LTUyVjUyWiIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtMiIgcG9pbnRzPSIxODAuMTcgNTIuMDEgMTUxLjk3IDM1LjczIDEyNC44NSA1MS4zOSAxNTMuMDUgNjcuNjcgMTgwLjE3IDUyLjAxIi8+PHBvbHlnb24gY2xhc3M9ImNscy0yIiBwb2ludHM9IjI3LjEyIDY3LjY3IDExNy4yMSAxNS42NiA5MC4wOCAwIDAgNTIuMDEgMjcuMTIgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTIiIHBvaW50cz0iNjEuODkgMTIwLjMgOTAuMDggMTM2LjU4IDExOC4yOCAxMjAuMyA5MC4wOCAxMDQuMDIgNjEuODkgMTIwLjMiLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDE1My4wNSAxNDAuMzcgOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyAwIDUyLjAxIDAgMTU2LjAzIDkwLjA4IDIwOC4wNCAxODAuMTcgMTU2LjAzIDE4MC4xNyA1Mi4wMSAxNTMuMDUgNjcuNjciLz48cG9seWdvbiBjbGFzcz0iY2xzLTMiIHBvaW50cz0iOTAuMDggNzEuNDYgNjEuODkgODcuNzQgNjEuODkgMTIwLjMgOTAuMDggMTA0LjAyIDExOC4yOCAxMjAuMyAxMTguMjggODcuNzQgOTAuMDggNzEuNDYiLz48cG9seWdvbiBjbGFzcz0iY2xzLTQiIHBvaW50cz0iMTUzLjA1IDY3LjY3IDExOC4yOCA4Ny43NCAxMTguMjggMTIwLjMgOTAuMDggMTM2LjU4IDkwLjA4IDE3Ni43MiAxNTMuMDUgMTQwLjM3IDE1My4wNSA2Ny42NyIvPjxwb2x5Z29uIGNsYXNzPSJjbHMtNSIgcG9pbnRzPSIyNy4xMiA2Ny42NyA2MS44OSA4Ny43NCA2MS44OSAxMjAuMyA5MC4wOCAxMzYuNTggOTAuMDggMTc2LjcyIDI3LjEyIDE0MC4zNyAyNy4xMiA2Ny42NyIvPjwvZz48L2c+PC9zdmc+";
}
else {
imgBack.src = DefaultLoadingScreen.DefaultLogoUrl;
}
imgBack.style.position = "absolute";
imgBack.style.left = "40%";
imgBack.style.top = "40%";
imgBack.style.width = "20%";
imgBack.style.height = "20%";
// Loading spinner
var imgSpinner = new Image();
if (!DefaultLoadingScreen.DefaultSpinnerUrl) {
imgSpinner.src = !svgSupport ? "https://cdn.babylonjs.com/Assets/loadingIcon.png" : "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAzOTIgMzkyIj48ZGVmcz48c3R5bGU+LmNscy0xe2ZpbGw6I2UwNjg0Yjt9LmNscy0ye2ZpbGw6bm9uZTt9PC9zdHlsZT48L2RlZnM+PHRpdGxlPlNwaW5uZXJJY29uPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU3Bpbm5lciI+PHBhdGggY2xhc3M9ImNscy0xIiBkPSJNNDAuMjEsMTI2LjQzYzMuNy03LjMxLDcuNjctMTQuNDQsMTItMjEuMzJsMy4zNi01LjEsMy41Mi01YzEuMjMtMS42MywyLjQxLTMuMjksMy42NS00LjkxczIuNTMtMy4yMSwzLjgyLTQuNzlBMTg1LjIsMTg1LjIsMCwwLDEsODMuNCw2Ny40M2EyMDgsMjA4LDAsMCwxLDE5LTE1LjY2YzMuMzUtMi40MSw2Ljc0LTQuNzgsMTAuMjUtN3M3LjExLTQuMjgsMTAuNzUtNi4zMmM3LjI5LTQsMTQuNzMtOCwyMi41My0xMS40OSwzLjktMS43Miw3Ljg4LTMuMywxMi00LjY0YTEwNC4yMiwxMDQuMjIsMCwwLDEsMTIuNDQtMy4yMyw2Mi40NCw2Mi40NCwwLDAsMSwxMi43OC0xLjM5QTI1LjkyLDI1LjkyLDAsMCwxLDE5NiwyMS40NGE2LjU1LDYuNTUsMCwwLDEsMi4wNSw5LDYuNjYsNi42NiwwLDAsMS0xLjY0LDEuNzhsLS40MS4yOWEyMi4wNywyMi4wNywwLDAsMS01Ljc4LDMsMzAuNDIsMzAuNDIsMCwwLDEtNS42NywxLjYyLDM3LjgyLDM3LjgyLDAsMCwxLTUuNjkuNzFjLTEsMC0xLjkuMTgtMi44NS4yNmwtMi44NS4yNHEtNS43Mi41MS0xMS40OCwxLjFjLTMuODQuNC03LjcxLjgyLTExLjU4LDEuNGExMTIuMzQsMTEyLjM0LDAsMCwwLTIyLjk0LDUuNjFjLTMuNzIsMS4zNS03LjM0LDMtMTAuOTQsNC42NHMtNy4xNCwzLjUxLTEwLjYsNS41MUExNTEuNiwxNTEuNiwwLDAsMCw2OC41Niw4N0M2Ny4yMyw4OC40OCw2Niw5MCw2NC42NCw5MS41NnMtMi41MSwzLjE1LTMuNzUsNC43M2wtMy41NCw0LjljLTEuMTMsMS42Ni0yLjIzLDMuMzUtMy4zMyw1YTEyNywxMjcsMCwwLDAtMTAuOTMsMjEuNDksMS41OCwxLjU4LDAsMSwxLTMtMS4xNVM0MC4xOSwxMjYuNDcsNDAuMjEsMTI2LjQzWiIvPjxyZWN0IGNsYXNzPSJjbHMtMiIgd2lkdGg9IjM5MiIgaGVpZ2h0PSIzOTIiLz48L2c+PC9nPjwvc3ZnPg==";
}
else {
imgSpinner.src = DefaultLoadingScreen.DefaultSpinnerUrl;
}
imgSpinner.style.position = "absolute";
imgSpinner.style.left = "30%";
imgSpinner.style.top = "30%";
imgSpinner.style.width = "40%";
imgSpinner.style.height = "40%";
imgSpinner.style.animation = "spin1 0.75s infinite linear";
imgSpinner.style.webkitAnimation = "spin1 0.75s infinite linear";
imgSpinner.style.transformOrigin = "50% 50%";
imgSpinner.style.webkitTransformOrigin = "50% 50%";
if (!svgSupport) {
var logoSize = { w: 16, h: 18.5 };
var loadingSize = { w: 30, h: 30 };
// set styling correctly
imgBack.style.width = logoSize.w + "vh";
imgBack.style.height = logoSize.h + "vh";
imgBack.style.left = "calc(50% - " + logoSize.w / 2 + "vh)";
imgBack.style.top = "calc(50% - " + logoSize.h / 2 + "vh)";
imgSpinner.style.width = loadingSize.w + "vh";
imgSpinner.style.height = loadingSize.h + "vh";
imgSpinner.style.left = "calc(50% - " + loadingSize.w / 2 + "vh)";
imgSpinner.style.top = "calc(50% - " + loadingSize.h / 2 + "vh)";
}
this._loadingDiv.appendChild(imgBack);
this._loadingDiv.appendChild(imgSpinner);
this._resizeLoadingUI();
window.addEventListener("resize", this._resizeLoadingUI);
this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
document.body.appendChild(this._loadingDiv);
this._loadingDiv.style.opacity = "1";
};
/**
* Function called to hide the loading screen
*/
DefaultLoadingScreen.prototype.hideLoadingUI = function () {
var _this = this;
if (!this._loadingDiv) {
return;
}
var onTransitionEnd = function () {
if (!_this._loadingDiv) {
return;
}
if (_this._loadingDiv.parentElement) {
_this._loadingDiv.parentElement.removeChild(_this._loadingDiv);
}
window.removeEventListener("resize", _this._resizeLoadingUI);
_this._loadingDiv = null;
};
this._loadingDiv.style.opacity = "0";
this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
};
Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
get: function () {
return this._loadingText;
},
/**
* Gets or sets the text to display while loading
*/
set: function (text) {
this._loadingText = text;
if (this._loadingTextDiv) {
this._loadingTextDiv.innerHTML = this._loadingText;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
/**
* Gets or sets the color to use for the background
*/
get: function () {
return this._loadingDivBackgroundColor;
},
set: function (color) {
this._loadingDivBackgroundColor = color;
if (!this._loadingDiv) {
return;
}
this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
},
enumerable: false,
configurable: true
});
/** Gets or sets the logo url to use for the default loading screen */
DefaultLoadingScreen.DefaultLogoUrl = "";
/** Gets or sets the spinner url to use for the default loading screen */
DefaultLoadingScreen.DefaultSpinnerUrl = "";
return DefaultLoadingScreen;
}());
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].DefaultLoadingScreenFactory = function (canvas) { return new DefaultLoadingScreen(canvas); };
/***/ }),
/***/ "./Loading/sceneLoader.ts":
/*!********************************!*\
!*** ./Loading/sceneLoader.ts ***!
\********************************/
/*! exports provided: SceneLoaderAnimationGroupLoadingMode, SceneLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderAnimationGroupLoadingMode", function() { return SceneLoaderAnimationGroupLoadingMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoader", function() { return SceneLoader; });
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Misc_filesInputStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Misc/filesInputStore */ "./Misc/filesInputStore.ts");
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../scene */ "./scene.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Engines/engineStore */ "./Engines/engineStore.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./sceneLoaderFlags */ "./Loading/sceneLoaderFlags.ts");
/**
* Mode that determines how to handle old animation groups before loading new ones.
*/
var SceneLoaderAnimationGroupLoadingMode;
(function (SceneLoaderAnimationGroupLoadingMode) {
/**
* Reset all old animations to initial state then dispose them.
*/
SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Clean"] = 0] = "Clean";
/**
* Stop all old animations.
*/
SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Stop"] = 1] = "Stop";
/**
* Restart old animations from first frame.
*/
SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["Sync"] = 2] = "Sync";
/**
* Old animations remains untouched.
*/
SceneLoaderAnimationGroupLoadingMode[SceneLoaderAnimationGroupLoadingMode["NoSync"] = 3] = "NoSync";
})(SceneLoaderAnimationGroupLoadingMode || (SceneLoaderAnimationGroupLoadingMode = {}));
/**
* Class used to load scene from various file formats using registered plugins
* @see https://doc.babylonjs.com/how_to/load_from_any_file_type
*/
var SceneLoader = /** @class */ (function () {
function SceneLoader() {
}
Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
/**
* Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
*/
get: function () {
return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ForceFullSceneLoadingForIncremental;
},
set: function (value) {
_sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ForceFullSceneLoadingForIncremental = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
/**
* Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
*/
get: function () {
return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ShowLoadingScreen;
},
set: function (value) {
_sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].ShowLoadingScreen = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneLoader, "loggingLevel", {
/**
* Defines the current logging level (while loading the scene)
* @ignorenaming
*/
get: function () {
return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].loggingLevel;
},
set: function (value) {
_sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].loggingLevel = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
/**
* Gets or set a boolean indicating if matrix weights must be cleaned upon loading
*/
get: function () {
return _sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].CleanBoneMatrixWeights;
},
set: function (value) {
_sceneLoaderFlags__WEBPACK_IMPORTED_MODULE_8__["SceneLoaderFlags"].CleanBoneMatrixWeights = value;
},
enumerable: false,
configurable: true
});
/**
* Gets the default plugin (used to load Babylon files)
* @returns the .babylon plugin
*/
SceneLoader.GetDefaultPlugin = function () {
return SceneLoader._registeredPlugins[".babylon"];
};
SceneLoader._GetPluginForExtension = function (extension) {
var registeredPlugin = SceneLoader._registeredPlugins[extension];
if (registeredPlugin) {
return registeredPlugin;
}
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: https://doc.babylonjs.com/how_to/load_from_any_file_type");
return SceneLoader.GetDefaultPlugin();
};
SceneLoader._GetPluginForDirectLoad = function (data) {
for (var extension in SceneLoader._registeredPlugins) {
var plugin = SceneLoader._registeredPlugins[extension].plugin;
if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
return SceneLoader._registeredPlugins[extension];
}
}
return SceneLoader.GetDefaultPlugin();
};
SceneLoader._GetPluginForFilename = function (sceneFilename) {
var queryStringPosition = sceneFilename.indexOf("?");
if (queryStringPosition !== -1) {
sceneFilename = sceneFilename.substring(0, queryStringPosition);
}
var dotPosition = sceneFilename.lastIndexOf(".");
var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
return SceneLoader._GetPluginForExtension(extension);
};
SceneLoader._GetDirectLoad = function (sceneFilename) {
if (sceneFilename.substr(0, 5) === "data:") {
return sceneFilename.substr(5);
}
return null;
};
SceneLoader._LoadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
var directLoad = SceneLoader._GetDirectLoad(fileInfo.name);
var registeredPlugin = pluginExtension ? SceneLoader._GetPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._GetPluginForDirectLoad(fileInfo.name) : SceneLoader._GetPluginForFilename(fileInfo.name));
var plugin;
if (registeredPlugin.plugin.createPlugin !== undefined) {
plugin = registeredPlugin.plugin.createPlugin();
}
else {
plugin = registeredPlugin.plugin;
}
if (!plugin) {
throw "The loader plugin corresponding to the file type you are trying to load has not been found. If using es6, please import the plugin you wish to use before.";
}
SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
if (directLoad) {
if (plugin.directLoad) {
var result = plugin.directLoad(scene, directLoad);
if (result.then) {
result.then(function (data) {
onSuccess(plugin, data);
}).catch(function (error) {
onError("Error in directLoad of _loadData: " + error, error);
});
}
else {
onSuccess(plugin, result);
}
}
else {
onSuccess(plugin, directLoad);
}
return plugin;
}
var useArrayBuffer = registeredPlugin.isBinary;
var dataCallback = function (data, responseURL) {
if (scene.isDisposed) {
onError("Scene has been disposed");
return;
}
onSuccess(plugin, data, responseURL);
};
var request = null;
var pluginDisposed = false;
var onDisposeObservable = plugin.onDisposeObservable;
if (onDisposeObservable) {
onDisposeObservable.add(function () {
pluginDisposed = true;
if (request) {
request.abort();
request = null;
}
onDispose();
});
}
var manifestChecked = function () {
if (pluginDisposed) {
return;
}
var successCallback = function (data, request) {
dataCallback(data, request ? request.responseURL : undefined);
};
var errorCallback = function (error) {
onError(error.message, error);
};
request = plugin.requestFile
? plugin.requestFile(scene, fileInfo.url, successCallback, onProgress, useArrayBuffer, errorCallback)
: scene._requestFile(fileInfo.url, successCallback, onProgress, true, useArrayBuffer, errorCallback);
};
var file = fileInfo.file || _Misc_filesInputStore__WEBPACK_IMPORTED_MODULE_2__["FilesInputStore"].FilesToLoad[fileInfo.name.toLowerCase()];
if (fileInfo.rootUrl.indexOf("file:") === -1 || (fileInfo.rootUrl.indexOf("file:") !== -1 && !file)) {
var engine = scene.getEngine();
var canUseOfflineSupport = engine.enableOfflineSupport;
if (canUseOfflineSupport) {
// Also check for exceptions
var exceptionFound = false;
for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
var regex = _a[_i];
if (regex.test(fileInfo.url)) {
exceptionFound = true;
break;
}
}
canUseOfflineSupport = !exceptionFound;
}
if (canUseOfflineSupport && _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].OfflineProviderFactory) {
// Checking if a manifest file has been set for this scene and if offline mode has been requested
scene.offlineProvider = _Engines_engine__WEBPACK_IMPORTED_MODULE_4__["Engine"].OfflineProviderFactory(fileInfo.url, manifestChecked, engine.disableManifestCheck);
}
else {
manifestChecked();
}
}
// Loading file from disk via input file or drag'n'drop
else {
if (file) {
var errorCallback = function (error) {
onError(error.message, error);
};
request = plugin.readFile
? plugin.readFile(scene, file, dataCallback, onProgress, useArrayBuffer, errorCallback)
: scene._readFile(file, dataCallback, onProgress, useArrayBuffer, errorCallback);
}
else {
onError("Unable to find file named " + fileInfo.name);
}
}
return plugin;
};
SceneLoader._GetFileInfo = function (rootUrl, sceneFilename) {
var url;
var name;
var file = null;
if (!sceneFilename) {
url = rootUrl;
name = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFilename(rootUrl);
rootUrl = _Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].GetFolderPath(rootUrl);
}
else if (sceneFilename.name) {
var sceneFile = sceneFilename;
url = rootUrl + sceneFile.name;
name = sceneFile.name;
file = sceneFile;
}
else {
var filename = sceneFilename;
if (filename.substr(0, 1) === "/") {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Wrong sceneFilename parameter");
return null;
}
url = rootUrl + filename;
name = filename;
}
return {
url: url,
rootUrl: rootUrl,
name: name,
file: file
};
};
// Public functions
/**
* Gets a plugin that can load the given extension
* @param extension defines the extension to load
* @returns a plugin or null if none works
*/
SceneLoader.GetPluginForExtension = function (extension) {
return SceneLoader._GetPluginForExtension(extension).plugin;
};
/**
* Gets a boolean indicating that the given extension can be loaded
* @param extension defines the extension to load
* @returns true if the extension is supported
*/
SceneLoader.IsPluginForExtensionAvailable = function (extension) {
return !!SceneLoader._registeredPlugins[extension];
};
/**
* Adds a new plugin to the list of registered plugins
* @param plugin defines the plugin to add
*/
SceneLoader.RegisterPlugin = function (plugin) {
if (typeof plugin.extensions === "string") {
var extension = plugin.extensions;
SceneLoader._registeredPlugins[extension.toLowerCase()] = {
plugin: plugin,
isBinary: false
};
}
else {
var extensions = plugin.extensions;
Object.keys(extensions).forEach(function (extension) {
SceneLoader._registeredPlugins[extension.toLowerCase()] = {
plugin: plugin,
isBinary: extensions[extension].isBinary
};
});
}
};
/**
* Import meshes into a scene
* @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene the instance of BABYLON.Scene to append to
* @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
* @param onProgress a callback with a progress event for each file being loaded
* @param onError a callback with the scene, a message, and possibly an exception when import fails
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded plugin
*/
SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (onSuccess === void 0) { onSuccess = null; }
if (onProgress === void 0) { onProgress = null; }
if (onError === void 0) { onError = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
if (!scene) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to import mesh to");
return null;
}
var fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);
if (!fileInfo) {
return null;
}
var loadingToken = {};
scene._addPendingData(loadingToken);
var disposeHandler = function () {
scene._removePendingData(loadingToken);
};
var errorHandler = function (message, exception) {
var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
if (onError) {
onError(scene, errorMessage, exception);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage);
// should the exception be thrown?
}
disposeHandler();
};
var progressHandler = onProgress ? function (event) {
try {
onProgress(event);
}
catch (e) {
errorHandler("Error in onProgress callback: " + e, e);
}
} : undefined;
var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
scene.importedMeshesFiles.push(fileInfo.url);
if (onSuccess) {
try {
onSuccess(meshes, particleSystems, skeletons, animationGroups);
}
catch (e) {
errorHandler("Error in onSuccess callback: " + e, e);
}
}
scene._removePendingData(loadingToken);
};
return SceneLoader._LoadData(fileInfo, scene, function (plugin, data, responseURL) {
if (plugin.rewriteRootURL) {
fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
}
if (plugin.importMesh) {
var syncedPlugin = plugin;
var meshes = new Array();
var particleSystems = new Array();
var skeletons = new Array();
if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
return;
}
scene.loadingPluginName = plugin.name;
successHandler(meshes, particleSystems, skeletons, []);
}
else {
var asyncedPlugin = plugin;
asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
scene.loadingPluginName = plugin.name;
successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
}).catch(function (error) {
errorHandler(error.message, error);
});
}
}, progressHandler, errorHandler, disposeHandler, pluginExtension);
};
/**
* Import meshes into a scene
* @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene the instance of BABYLON.Scene to append to
* @param onProgress a callback with a progress event for each file being loaded
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
*/
SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (onProgress === void 0) { onProgress = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
return new Promise(function (resolve, reject) {
SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
resolve({
meshes: meshes,
particleSystems: particleSystems,
skeletons: skeletons,
animationGroups: animationGroups
});
}, onProgress, function (scene, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
/**
* Load a scene
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param engine is the instance of BABYLON.Engine to use to create the scene
* @param onSuccess a callback with the scene when import succeeds
* @param onProgress a callback with a progress event for each file being loaded
* @param onError a callback with the scene, a message, and possibly an exception when import fails
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded plugin
*/
SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (engine === void 0) { engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedEngine; }
if (onSuccess === void 0) { onSuccess = null; }
if (onProgress === void 0) { onProgress = null; }
if (onError === void 0) { onError = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
if (!engine) {
_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("No engine available");
return null;
}
return SceneLoader.Append(rootUrl, sceneFilename, new _scene__WEBPACK_IMPORTED_MODULE_3__["Scene"](engine), onSuccess, onProgress, onError, pluginExtension);
};
/**
* Load a scene
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param engine is the instance of BABYLON.Engine to use to create the scene
* @param onProgress a callback with a progress event for each file being loaded
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded scene
*/
SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (engine === void 0) { engine = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedEngine; }
if (onProgress === void 0) { onProgress = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
return new Promise(function (resolve, reject) {
SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
resolve(scene);
}, onProgress, function (scene, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
/**
* Append a scene
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene is the instance of BABYLON.Scene to append to
* @param onSuccess a callback with the scene when import succeeds
* @param onProgress a callback with a progress event for each file being loaded
* @param onError a callback with the scene, a message, and possibly an exception when import fails
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded plugin
*/
SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
var _this = this;
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (onSuccess === void 0) { onSuccess = null; }
if (onProgress === void 0) { onProgress = null; }
if (onError === void 0) { onError = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
if (!scene) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to append to");
return null;
}
var fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);
if (!fileInfo) {
return null;
}
if (SceneLoader.ShowLoadingScreen && !this._showingLoadingScreen) {
this._showingLoadingScreen = true;
scene.getEngine().displayLoadingUI();
scene.executeWhenReady(function () {
scene.getEngine().hideLoadingUI();
_this._showingLoadingScreen = false;
});
}
var loadingToken = {};
scene._addPendingData(loadingToken);
var disposeHandler = function () {
scene._removePendingData(loadingToken);
};
var errorHandler = function (message, exception) {
var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
if (onError) {
onError(scene, errorMessage, exception);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage);
// should the exception be thrown?
}
disposeHandler();
};
var progressHandler = onProgress ? function (event) {
try {
onProgress(event);
}
catch (e) {
errorHandler("Error in onProgress callback", e);
}
} : undefined;
var successHandler = function () {
if (onSuccess) {
try {
onSuccess(scene);
}
catch (e) {
errorHandler("Error in onSuccess callback", e);
}
}
scene._removePendingData(loadingToken);
};
return SceneLoader._LoadData(fileInfo, scene, function (plugin, data) {
if (plugin.load) {
var syncedPlugin = plugin;
if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
return;
}
scene.loadingPluginName = plugin.name;
successHandler();
}
else {
var asyncedPlugin = plugin;
asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
scene.loadingPluginName = plugin.name;
successHandler();
}).catch(function (error) {
errorHandler(error.message, error);
});
}
}, progressHandler, errorHandler, disposeHandler, pluginExtension);
};
/**
* Append a scene
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene is the instance of BABYLON.Scene to append to
* @param onProgress a callback with a progress event for each file being loaded
* @param pluginExtension the extension used to determine the plugin
* @returns The given scene
*/
SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (onProgress === void 0) { onProgress = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
return new Promise(function (resolve, reject) {
SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
resolve(scene);
}, onProgress, function (scene, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
/**
* Load a scene into an asset container
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
* @param onSuccess a callback with the scene when import succeeds
* @param onProgress a callback with a progress event for each file being loaded
* @param onError a callback with the scene, a message, and possibly an exception when import fails
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded plugin
*/
SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (onSuccess === void 0) { onSuccess = null; }
if (onProgress === void 0) { onProgress = null; }
if (onError === void 0) { onError = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
if (!scene) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to load asset container to");
return null;
}
var fileInfo = SceneLoader._GetFileInfo(rootUrl, sceneFilename);
if (!fileInfo) {
return null;
}
var loadingToken = {};
scene._addPendingData(loadingToken);
var disposeHandler = function () {
scene._removePendingData(loadingToken);
};
var errorHandler = function (message, exception) {
var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
if (exception && exception.message) {
errorMessage += " (" + exception.message + ")";
}
if (onError) {
onError(scene, errorMessage, exception);
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error(errorMessage);
// should the exception be thrown?
}
disposeHandler();
};
var progressHandler = onProgress ? function (event) {
try {
onProgress(event);
}
catch (e) {
errorHandler("Error in onProgress callback", e);
}
} : undefined;
var successHandler = function (assets) {
if (onSuccess) {
try {
onSuccess(assets);
}
catch (e) {
errorHandler("Error in onSuccess callback", e);
}
}
scene._removePendingData(loadingToken);
};
return SceneLoader._LoadData(fileInfo, scene, function (plugin, data) {
if (plugin.loadAssetContainer) {
var syncedPlugin = plugin;
var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
if (!assetContainer) {
return;
}
scene.loadingPluginName = plugin.name;
successHandler(assetContainer);
}
else if (plugin.loadAssetContainerAsync) {
var asyncedPlugin = plugin;
asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
scene.loadingPluginName = plugin.name;
successHandler(assetContainer);
}).catch(function (error) {
errorHandler(error.message, error);
});
}
else {
errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
}
}, progressHandler, errorHandler, disposeHandler, pluginExtension);
};
/**
* Load a scene into an asset container
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene (default: empty string)
* @param scene is the instance of Scene to append to
* @param onProgress a callback with a progress event for each file being loaded
* @param pluginExtension the extension used to determine the plugin
* @returns The loaded asset container
*/
SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (onProgress === void 0) { onProgress = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
return new Promise(function (resolve, reject) {
SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
resolve(assetContainer);
}, onProgress, function (scene, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
/**
* Import animations from a file into a scene
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
* @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise
* @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones
* @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)
* @param onSuccess a callback with the scene when import succeeds
* @param onProgress a callback with a progress event for each file being loaded
* @param onError a callback with the scene, a message, and possibly an exception when import fails
* @param pluginExtension the extension used to determine the plugin
*/
SceneLoader.ImportAnimations = function (rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (overwriteAnimations === void 0) { overwriteAnimations = true; }
if (animationGroupLoadingMode === void 0) { animationGroupLoadingMode = SceneLoaderAnimationGroupLoadingMode.Clean; }
if (targetConverter === void 0) { targetConverter = null; }
if (onSuccess === void 0) { onSuccess = null; }
if (onProgress === void 0) { onProgress = null; }
if (onError === void 0) { onError = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
if (!scene) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("No scene available to load animations to");
return;
}
if (overwriteAnimations) {
// Reset, stop and dispose all animations before loading new ones
for (var _i = 0, _a = scene.animatables; _i < _a.length; _i++) {
var animatable = _a[_i];
animatable.reset();
}
scene.stopAllAnimations();
scene.animationGroups.slice().forEach(function (animationGroup) {
animationGroup.dispose();
});
var nodes = scene.getNodes();
nodes.forEach(function (node) {
if (node.animations) {
node.animations = [];
}
});
}
else {
switch (animationGroupLoadingMode) {
case SceneLoaderAnimationGroupLoadingMode.Clean:
scene.animationGroups.slice().forEach(function (animationGroup) {
animationGroup.dispose();
});
break;
case SceneLoaderAnimationGroupLoadingMode.Stop:
scene.animationGroups.forEach(function (animationGroup) {
animationGroup.stop();
});
break;
case SceneLoaderAnimationGroupLoadingMode.Sync:
scene.animationGroups.forEach(function (animationGroup) {
animationGroup.reset();
animationGroup.restart();
});
break;
case SceneLoaderAnimationGroupLoadingMode.NoSync:
// nothing to do
break;
default:
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Error("Unknown animation group loading mode value '" + animationGroupLoadingMode + "'");
return;
}
}
var startingIndexForNewAnimatables = scene.animatables.length;
var onAssetContainerLoaded = function (container) {
container.mergeAnimationsTo(scene, scene.animatables.slice(startingIndexForNewAnimatables), targetConverter);
container.dispose();
scene.onAnimationFileImportedObservable.notifyObservers(scene);
if (onSuccess) {
onSuccess(scene);
}
};
this.LoadAssetContainer(rootUrl, sceneFilename, scene, onAssetContainerLoaded, onProgress, onError, pluginExtension);
};
/**
* Import animations from a file into a scene
* @param rootUrl a string that defines the root url for the scene and resources or the concatenation of rootURL and filename (e.g. http://example.com/test.glb)
* @param sceneFilename a string that defines the name of the scene file or starts with "data:" following by the stringified version of the scene or a File object (default: empty string)
* @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
* @param overwriteAnimations when true, animations are cleaned before importing new ones. Animations are appended otherwise
* @param animationGroupLoadingMode defines how to handle old animations groups before importing new ones
* @param targetConverter defines a function used to convert animation targets from loaded scene to current scene (default: search node by name)
* @param onSuccess a callback with the scene when import succeeds
* @param onProgress a callback with a progress event for each file being loaded
* @param onError a callback with the scene, a message, and possibly an exception when import fails
* @param pluginExtension the extension used to determine the plugin
* @returns the updated scene with imported animations
*/
SceneLoader.ImportAnimationsAsync = function (rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, onSuccess, onProgress, onError, pluginExtension) {
if (sceneFilename === void 0) { sceneFilename = ""; }
if (scene === void 0) { scene = _Engines_engineStore__WEBPACK_IMPORTED_MODULE_5__["EngineStore"].LastCreatedScene; }
if (overwriteAnimations === void 0) { overwriteAnimations = true; }
if (animationGroupLoadingMode === void 0) { animationGroupLoadingMode = SceneLoaderAnimationGroupLoadingMode.Clean; }
if (targetConverter === void 0) { targetConverter = null; }
if (onSuccess === void 0) { onSuccess = null; }
if (onProgress === void 0) { onProgress = null; }
if (onError === void 0) { onError = null; }
if (pluginExtension === void 0) { pluginExtension = null; }
return new Promise(function (resolve, reject) {
SceneLoader.ImportAnimations(rootUrl, sceneFilename, scene, overwriteAnimations, animationGroupLoadingMode, targetConverter, function (_scene) {
resolve(_scene);
}, onProgress, function (_scene, message, exception) {
reject(exception || new Error(message));
}, pluginExtension);
});
};
/**
* No logging while loading
*/
SceneLoader.NO_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_NO_LOGGING;
/**
* Minimal logging while loading
*/
SceneLoader.MINIMAL_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_MINIMAL_LOGGING;
/**
* Summary logging while loading
*/
SceneLoader.SUMMARY_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_SUMMARY_LOGGING;
/**
* Detailled logging while loading
*/
SceneLoader.DETAILED_LOGGING = _Engines_constants__WEBPACK_IMPORTED_MODULE_7__["Constants"].SCENELOADER_DETAILED_LOGGING;
// Members
/**
* Event raised when a plugin is used to load a scene
*/
SceneLoader.OnPluginActivatedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_1__["Observable"]();
SceneLoader._registeredPlugins = {};
SceneLoader._showingLoadingScreen = false;
return SceneLoader;
}());
/***/ }),
/***/ "./Loading/sceneLoaderFlags.ts":
/*!*************************************!*\
!*** ./Loading/sceneLoaderFlags.ts ***!
\*************************************/
/*! exports provided: SceneLoaderFlags */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SceneLoaderFlags", function() { return SceneLoaderFlags; });
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../Engines/constants */ "./Engines/constants.ts");
/**
* Class used to represent data loading progression
*/
var SceneLoaderFlags = /** @class */ (function () {
function SceneLoaderFlags() {
}
Object.defineProperty(SceneLoaderFlags, "ForceFullSceneLoadingForIncremental", {
/**
* Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
*/
get: function () {
return SceneLoaderFlags._ForceFullSceneLoadingForIncremental;
},
set: function (value) {
SceneLoaderFlags._ForceFullSceneLoadingForIncremental = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneLoaderFlags, "ShowLoadingScreen", {
/**
* Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
*/
get: function () {
return SceneLoaderFlags._ShowLoadingScreen;
},
set: function (value) {
SceneLoaderFlags._ShowLoadingScreen = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneLoaderFlags, "loggingLevel", {
/**
* Defines the current logging level (while loading the scene)
* @ignorenaming
*/
get: function () {
return SceneLoaderFlags._loggingLevel;
},
set: function (value) {
SceneLoaderFlags._loggingLevel = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(SceneLoaderFlags, "CleanBoneMatrixWeights", {
/**
* Gets or set a boolean indicating if matrix weights must be cleaned upon loading
*/
get: function () {
return SceneLoaderFlags._CleanBoneMatrixWeights;
},
set: function (value) {
SceneLoaderFlags._CleanBoneMatrixWeights = value;
},
enumerable: false,
configurable: true
});
// Flags
SceneLoaderFlags._ForceFullSceneLoadingForIncremental = false;
SceneLoaderFlags._ShowLoadingScreen = true;
SceneLoaderFlags._CleanBoneMatrixWeights = false;
SceneLoaderFlags._loggingLevel = _Engines_constants__WEBPACK_IMPORTED_MODULE_0__["Constants"].SCENELOADER_NO_LOGGING;
return SceneLoaderFlags;
}());
/***/ }),
/***/ "./Materials/Background/backgroundMaterial.ts":
/*!****************************************************!*\
!*** ./Materials/Background/backgroundMaterial.ts ***!
\****************************************************/
/*! exports provided: BackgroundMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return BackgroundMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts");
/* harmony import */ var _Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Materials/pushMaterial */ "./Materials/pushMaterial.ts");
/* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Shaders_background_fragment__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Shaders/background.fragment */ "./Shaders/background.fragment.ts");
/* harmony import */ var _Shaders_background_vertex__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Shaders/background.vertex */ "./Shaders/background.vertex.ts");
/* harmony import */ var _effectFallbacks__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../effectFallbacks */ "./Materials/effectFallbacks.ts");
/**
* Background material defines definition.
* @hidden Mainly internal Use
*/
var BackgroundMaterialDefines = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BackgroundMaterialDefines, _super);
/**
* Constructor of the defines.
*/
function BackgroundMaterialDefines() {
var _this = _super.call(this) || this;
/**
* True if the diffuse texture is in use.
*/
_this.DIFFUSE = false;
/**
* The direct UV channel to use.
*/
_this.DIFFUSEDIRECTUV = 0;
/**
* True if the diffuse texture is in gamma space.
*/
_this.GAMMADIFFUSE = false;
/**
* True if the diffuse texture has opacity in the alpha channel.
*/
_this.DIFFUSEHASALPHA = false;
/**
* True if you want the material to fade to transparent at grazing angle.
*/
_this.OPACITYFRESNEL = false;
/**
* True if an extra blur needs to be added in the reflection.
*/
_this.REFLECTIONBLUR = false;
/**
* True if you want the material to fade to reflection at grazing angle.
*/
_this.REFLECTIONFRESNEL = false;
/**
* True if you want the material to falloff as far as you move away from the scene center.
*/
_this.REFLECTIONFALLOFF = false;
/**
* False if the current Webgl implementation does not support the texture lod extension.
*/
_this.TEXTURELODSUPPORT = false;
/**
* True to ensure the data are premultiplied.
*/
_this.PREMULTIPLYALPHA = false;
/**
* True if the texture contains cooked RGB values and not gray scaled multipliers.
*/
_this.USERGBCOLOR = false;
/**
* True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
* stays aligned with the desired configuration.
*/
_this.USEHIGHLIGHTANDSHADOWCOLORS = false;
/**
* True if only shadows must be rendered
*/
_this.BACKMAT_SHADOWONLY = false;
/**
* True to add noise in order to reduce the banding effect.
*/
_this.NOISE = false;
/**
* is the reflection texture in BGR color scheme?
* Mainly used to solve a bug in ios10 video tag
*/
_this.REFLECTIONBGR = false;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.MULTIVIEW = false;
// Reflection.
_this.REFLECTION = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.REFLECTIONMAP_OPPOSITEZ = false;
_this.LODINREFLECTIONALPHA = false;
_this.GAMMAREFLECTION = false;
_this.RGBDREFLECTION = false;
_this.EQUIRECTANGULAR_RELFECTION_FOV = false;
// Default BJS.
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.UV1 = false;
_this.UV2 = false;
_this.CLIPPLANE = false;
_this.CLIPPLANE2 = false;
_this.CLIPPLANE3 = false;
_this.CLIPPLANE4 = false;
_this.CLIPPLANE5 = false;
_this.CLIPPLANE6 = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.NORMAL = false;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.INSTANCES = false;
_this.SHADOWFLOAT = false;
_this.rebuild();
return _this;
}
return BackgroundMaterialDefines;
}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_7__["MaterialDefines"]));
/**
* Background material used to create an efficient environement around your scene.
*/
var BackgroundMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BackgroundMaterial, _super);
/**
* Instantiates a Background Material in the given scene
* @param name The friendly name of the material
* @param scene The scene to add the material to
*/
function BackgroundMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Key light Color (multiply against the environement texture)
*/
_this.primaryColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__["Color3"].White();
_this._primaryColorShadowLevel = 0;
_this._primaryColorHighlightLevel = 0;
/**
* Reflection Texture used in the material.
* Should be author in a specific way for the best result (refer to the documentation).
*/
_this.reflectionTexture = null;
/**
* Reflection Texture level of blur.
*
* Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
* texture twice.
*/
_this.reflectionBlur = 0;
/**
* Diffuse Texture used in the material.
* Should be author in a specific way for the best result (refer to the documentation).
*/
_this.diffuseTexture = null;
_this._shadowLights = null;
/**
* Specify the list of lights casting shadow on the material.
* All scene shadow lights will be included if null.
*/
_this.shadowLights = null;
/**
* Helps adjusting the shadow to a softer level if required.
* 0 means black shadows and 1 means no shadows.
*/
_this.shadowLevel = 0;
/**
* In case of opacity Fresnel or reflection falloff, this is use as a scene center.
* It is usually zero but might be interesting to modify according to your setup.
*/
_this.sceneCenter = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector3"].Zero();
/**
* This helps specifying that the material is falling off to the sky box at grazing angle.
* This helps ensuring a nice transition when the camera goes under the ground.
*/
_this.opacityFresnel = true;
/**
* This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
* This helps adding a mirror texture on the ground.
*/
_this.reflectionFresnel = false;
/**
* This helps specifying the falloff radius off the reflection texture from the sceneCenter.
* This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
*/
_this.reflectionFalloffDistance = 0.0;
/**
* This specifies the weight of the reflection against the background in case of reflection Fresnel.
*/
_this.reflectionAmount = 1.0;
/**
* This specifies the weight of the reflection at grazing angle.
*/
_this.reflectionReflectance0 = 0.05;
/**
* This specifies the weight of the reflection at a perpendicular point of view.
*/
_this.reflectionReflectance90 = 0.5;
/**
* Helps to directly use the maps channels instead of their level.
*/
_this.useRGBColor = true;
/**
* This helps reducing the banding effect that could occur on the background.
*/
_this.enableNoise = false;
_this._fovMultiplier = 1.0;
/**
* Enable the FOV adjustment feature controlled by fovMultiplier.
*/
_this.useEquirectangularFOV = false;
_this._maxSimultaneousLights = 4;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this.maxSimultaneousLights = 4;
_this._shadowOnly = false;
/**
* Make the material only render shadows
*/
_this.shadowOnly = false;
/**
* Keep track of the image processing observer to allow dispose and replace.
*/
_this._imageProcessingObserver = null;
/**
* Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
* Setting this flag to true (not done automatically!) will convert it back to RGB.
*/
_this.switchToBGR = false;
// Temp values kept as cache in the material.
_this._renderTargets = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_2__["SmartArray"](16);
_this._reflectionControls = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector4"].Zero();
_this._white = _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__["Color3"].White();
_this._primaryShadowColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__["Color3"].Black();
_this._primaryHighlightColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_14__["Color3"].Black();
// Setup the default processing configuration to the scene.
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function () {
_this._renderTargets.reset();
if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
_this._renderTargets.push(_this._diffuseTexture);
}
if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
return _this._renderTargets;
};
return _this;
}
Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
/**
* Experimental Internal Use Only.
*
* Key light Color in "perceptual value" meaning the color you would like to see on screen.
* This acts as a helper to set the primary color to a more "human friendly" value.
* Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
* output color as close as possible from the chosen value.
* (This does not account for contrast color grading and color curves as they are considered post effect and not directly
* part of lighting setup.)
*/
get: function () {
return this.__perceptualColor;
},
set: function (value) {
this.__perceptualColor = value;
this._computePrimaryColorFromPerceptualColor();
this._markAllSubMeshesAsLightsDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
/**
* Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
* The color opposite to the primary color is used at the level chosen to define what the black area would look.
*/
get: function () {
return this._primaryColorShadowLevel;
},
set: function (value) {
this._primaryColorShadowLevel = value;
this._computePrimaryColors();
this._markAllSubMeshesAsLightsDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
/**
* Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
* The primary color is used at the level chosen to define what the white area would look.
*/
get: function () {
return this._primaryColorHighlightLevel;
},
set: function (value) {
this._primaryColorHighlightLevel = value;
this._computePrimaryColors();
this._markAllSubMeshesAsLightsDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
/**
* Sets the reflection reflectance fresnel values according to the default standard
* empirically know to work well :-)
*/
set: function (value) {
var reflectionWeight = value;
if (reflectionWeight < 0.5) {
reflectionWeight = reflectionWeight * 2.0;
this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
}
else {
reflectionWeight = reflectionWeight * 2.0 - 1.0;
this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
/**
* The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
* Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
* Recommended to be keep at 1.0 except for special cases.
*/
get: function () {
return this._fovMultiplier;
},
set: function (value) {
if (isNaN(value)) {
value = 1.0;
}
this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
},
enumerable: false,
configurable: true
});
/**
* Attaches a new image processing configuration to the PBR Material.
* @param configuration (if null the scene configuration will be use)
*/
BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
// Detaches observer.
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
// Pick the scene configuration if needed.
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
}
else {
this._imageProcessingConfiguration = configuration;
}
// Attaches observer.
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () {
_this._computePrimaryColorFromPerceptualColor();
_this._markAllSubMeshesAsImageProcessingDirty();
});
}
};
Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function () {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function (value) {
this._attachImageProcessingConfiguration(value);
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function () {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function (value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function () {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function (value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function () {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function (value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function () {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function (value) {
this.imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function () {
return this.imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function (value) {
this.imageProcessingConfiguration.colorCurves = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
/**
* Gets a boolean indicating that current material needs to register RTT
*/
get: function () {
if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
return true;
}
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
return true;
}
return false;
},
enumerable: false,
configurable: true
});
/**
* The entire material has been created in order to prevent overdraw.
* @returns false
*/
BackgroundMaterial.prototype.needAlphaTesting = function () {
return true;
};
/**
* The entire material has been created in order to prevent overdraw.
* @returns true if blending is enable
*/
BackgroundMaterial.prototype.needAlphaBlending = function () {
return (this.alpha < 1) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha) || this._shadowOnly;
};
/**
* Checks wether the material is ready to be rendered for a given mesh.
* @param mesh The mesh to render
* @param subMesh The submesh to check against
* @param useInstances Specify wether or not the material is used with instances
* @returns true if all the dependencies are ready (Textures, Effects...)
*/
BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
var _this = this;
if (useInstances === void 0) { useInstances = false; }
if (subMesh.effect && this.isFrozen) {
if (subMesh.effect._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new BackgroundMaterialDefines();
}
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (this._isReadyForSubMesh(subMesh)) {
return true;
}
var engine = scene.getEngine();
// Lights
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
defines._needNormals = true;
// Multiview
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines);
// Textures
if (defines._areTexturesDirty) {
defines._needUVs = false;
if (scene.texturesEnabled) {
if (scene.getEngine().getCaps().textureLOD) {
defines.TEXTURELODSUPPORT = true;
}
if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_13__["MaterialFlags"].DiffuseTextureEnabled) {
if (!this._diffuseTexture.isReadyOrNotBlocking()) {
return false;
}
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
defines.OPACITYFRESNEL = this._opacityFresnel;
}
else {
defines.DIFFUSE = false;
defines.DIFFUSEHASALPHA = false;
defines.GAMMADIFFUSE = false;
defines.OPACITYFRESNEL = false;
}
var reflectionTexture = this._reflectionTexture;
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_13__["MaterialFlags"].ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.RGBDREFLECTION = reflectionTexture.isRGBD;
defines.REFLECTIONBLUR = this._reflectionBlur > 0;
defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
defines.REFLECTIONBGR = this.switchToBGR;
if (reflectionTexture.coordinatesMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].INVCUBIC_MODE) {
defines.INVERTCUBICMAP = true;
}
defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
switch (reflectionTexture.coordinatesMode) {
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].EXPLICIT_MODE:
defines.REFLECTIONMAP_EXPLICIT = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].PLANAR_MODE:
defines.REFLECTIONMAP_PLANAR = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].PROJECTION_MODE:
defines.REFLECTIONMAP_PROJECTION = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].SKYBOX_MODE:
defines.REFLECTIONMAP_SKYBOX = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].SPHERICAL_MODE:
defines.REFLECTIONMAP_SPHERICAL = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].FIXED_EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].CUBIC_MODE:
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].INVCUBIC_MODE:
default:
defines.REFLECTIONMAP_CUBIC = true;
break;
}
if (this.reflectionFresnel) {
defines.REFLECTIONFRESNEL = true;
defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
this._reflectionControls.x = this.reflectionAmount;
this._reflectionControls.y = this.reflectionReflectance0;
this._reflectionControls.z = this.reflectionReflectance90;
this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
}
else {
defines.REFLECTIONFRESNEL = false;
defines.REFLECTIONFALLOFF = false;
}
}
else {
defines.REFLECTION = false;
defines.REFLECTIONFRESNEL = false;
defines.REFLECTIONFALLOFF = false;
defines.REFLECTIONBLUR = false;
defines.REFLECTIONMAP_3D = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
defines.INVERTCUBICMAP = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
defines.RGBDREFLECTION = false;
}
}
defines.PREMULTIPLYALPHA = (this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_PREMULTIPLIED || this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_11__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF);
defines.USERGBCOLOR = this._useRGBColor;
defines.NOISE = this._enableNoise;
}
if (defines._areLightsDirty) {
defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
defines.BACKMAT_SHADOWONLY = this._shadowOnly;
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
this._imageProcessingConfiguration.prepareDefines(defines);
}
// Misc.
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
// Values that need to be evaluated on every frame
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
// Attribs
if (_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
if (mesh) {
if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind)) {
mesh.createNormals(true);
_Misc_logger__WEBPACK_IMPORTED_MODULE_3__["Logger"].Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
}
}
}
// Get correct effect
if (defines.isDirty) {
defines.markAsProcessed();
scene.resetCachedMaterial();
// Fallbacks
var fallbacks = new _effectFallbacks__WEBPACK_IMPORTED_MODULE_17__["EffectFallbacks"]();
if (defines.FOG) {
fallbacks.addFallback(0, "FOG");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(1, "POINTSIZE");
}
if (defines.MULTIVIEW) {
fallbacks.addFallback(0, "MULTIVIEW");
}
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
//Attributes
var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind];
if (defines.NORMAL) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind);
}
if (defines.UV1) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UVKind);
}
if (defines.UV2) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UV2Kind);
}
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareAttributesForInstances(attribs, defines);
var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
"vFogInfos", "vFogColor", "pointSize",
"vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "mBones",
"vPrimaryColor", "vPrimaryColorShadow",
"vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
"shadowLevel", "alpha",
"vBackgroundCenter", "vReflectionControl",
"vDiffuseInfos", "diffuseMatrix",
];
var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
var uniformBuffers = ["Material", "Scene"];
if (_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_9__["ImageProcessingConfiguration"]) {
_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_9__["ImageProcessingConfiguration"].PrepareUniforms(uniforms, defines);
_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_9__["ImageProcessingConfiguration"].PrepareSamplers(samplers, defines);
}
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
var onCompiled = function (effect) {
if (_this.onCompiled) {
_this.onCompiled(effect);
}
_this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
};
var join = defines.toString();
subMesh.setEffect(scene.getEngine().createEffect("background", {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: join,
fallbacks: fallbacks,
onCompiled: onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
}, engine), defines);
this.buildUniformLayout();
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
subMesh.effect._wasPreviouslyReady = true;
return true;
};
/**
* Compute the primary color according to the chosen perceptual color.
*/
BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
if (!this.__perceptualColor) {
return;
}
this._primaryColor.copyFrom(this.__perceptualColor);
// Revert gamma space.
this._primaryColor.toLinearSpaceToRef(this._primaryColor);
// Revert image processing configuration.
if (this._imageProcessingConfiguration) {
// Revert Exposure.
this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
}
this._computePrimaryColors();
};
/**
* Compute the highlights and shadow colors according to their chosen levels.
*/
BackgroundMaterial.prototype._computePrimaryColors = function () {
if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
return;
}
// Find the highlight color based on the configuration.
this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
// Find the shadow color based on the configuration.
this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
};
/**
* Build the uniform buffer used in the material.
*/
BackgroundMaterial.prototype.buildUniformLayout = function () {
// Order is important !
this._uniformBuffer.addUniform("vPrimaryColor", 4);
this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
this._uniformBuffer.addUniform("vDiffuseInfos", 2);
this._uniformBuffer.addUniform("vReflectionInfos", 2);
this._uniformBuffer.addUniform("diffuseMatrix", 16);
this._uniformBuffer.addUniform("reflectionMatrix", 16);
this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
this._uniformBuffer.addUniform("fFovMultiplier", 1);
this._uniformBuffer.addUniform("pointSize", 1);
this._uniformBuffer.addUniform("shadowLevel", 1);
this._uniformBuffer.addUniform("alpha", 1);
this._uniformBuffer.addUniform("vBackgroundCenter", 3);
this._uniformBuffer.addUniform("vReflectionControl", 4);
this._uniformBuffer.create();
};
/**
* Unbind the material.
*/
BackgroundMaterial.prototype.unbind = function () {
if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
this._uniformBuffer.setTexture("diffuseSampler", null);
}
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._uniformBuffer.setTexture("reflectionSampler", null);
}
_super.prototype.unbind.call(this);
};
/**
* Bind only the world matrix to the material.
* @param world The world matrix to bind.
*/
BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
this._activeEffect.setMatrix("world", world);
};
/**
* Bind the material for a dedicated submeh (every used meshes will be considered opaque).
* @param world The world matrix to bind.
* @param subMesh The submesh to bind for.
*/
BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
// Matrices
this.bindOnlyWorldMatrix(world);
// Bones
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].BindBonesParameters(mesh, this._activeEffect);
var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
if (mustRebind) {
this._uniformBuffer.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
var reflectionTexture = this._reflectionTexture;
if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
// Texture uniforms
if (scene.texturesEnabled) {
if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_13__["MaterialFlags"].DiffuseTextureEnabled) {
this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
}
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_13__["MaterialFlags"].ReflectionTextureEnabled) {
this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
}
}
if (this.shadowLevel > 0) {
this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
}
this._uniformBuffer.updateFloat("alpha", this.alpha);
// Point size
if (this.pointsCloud) {
this._uniformBuffer.updateFloat("pointSize", this.pointSize);
}
if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
}
else {
this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
}
}
this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
// Textures
if (scene.texturesEnabled) {
if (this._diffuseTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_13__["MaterialFlags"].DiffuseTextureEnabled) {
this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
}
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_13__["MaterialFlags"].ReflectionTextureEnabled) {
if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
}
else if (!defines.REFLECTIONBLUR) {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
}
else {
this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
}
if (defines.REFLECTIONFRESNEL) {
this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
}
}
}
// Clip plane
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].BindClipPlane(this._activeEffect, scene);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].BindEyePosition(effect, scene);
}
if (mustRebind || !this.isFrozen) {
if (scene.lightsEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
}
// View
this.bindView(effect);
// Fog
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_6__["MaterialHelper"].BindFogParameters(scene, mesh, this._activeEffect, true);
// image processing
if (this._imageProcessingConfiguration) {
this._imageProcessingConfiguration.bind(this._activeEffect);
}
}
this._uniformBuffer.update();
this._afterBind(mesh, this._activeEffect);
};
/**
* Checks to see if a texture is used in the material.
* @param texture - Base texture to use.
* @returns - Boolean specifying if a texture is used in the material.
*/
BackgroundMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this._reflectionTexture === texture) {
return true;
}
if (this._diffuseTexture === texture) {
return true;
}
return false;
};
/**
* Dispose the material.
* @param forceDisposeEffect Force disposal of the associated effect.
* @param forceDisposeTextures Force disposal of the associated textures.
*/
BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
if (forceDisposeTextures) {
if (this.diffuseTexture) {
this.diffuseTexture.dispose();
}
if (this.reflectionTexture) {
this.reflectionTexture.dispose();
}
}
this._renderTargets.dispose();
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect);
};
/**
* Clones the material.
* @param name The cloned name.
* @returns The cloned material.
*/
BackgroundMaterial.prototype.clone = function (name) {
var _this = this;
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
};
/**
* Serializes the current material to its JSON representation.
* @returns The JSON representation.
*/
BackgroundMaterial.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.BackgroundMaterial";
return serializationObject;
};
/**
* Gets the class name of the material
* @returns "BackgroundMaterial"
*/
BackgroundMaterial.prototype.getClassName = function () {
return "BackgroundMaterial";
};
/**
* Parse a JSON input to create back a background material.
* @param source The JSON data to parse
* @param scene The scene to create the parsed material in
* @param rootUrl The root url of the assets the material depends upon
* @returns the instantiated BackgroundMaterial.
*/
BackgroundMaterial.Parse = function (source, scene, rootUrl) {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
};
/**
* Standard reflectance value at parallel view angle.
*/
BackgroundMaterial.StandardReflectance0 = 0.05;
/**
* Standard reflectance value at grazing angle.
*/
BackgroundMaterial.StandardReflectance90 = 0.5;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], BackgroundMaterial.prototype, "_primaryColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial.prototype, "primaryColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], BackgroundMaterial.prototype, "__perceptualColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])()
], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionBlur", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])()
], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "diffuseTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "shadowLights", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_shadowLevel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "shadowLevel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector3"])()
], BackgroundMaterial.prototype, "_sceneCenter", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "sceneCenter", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "opacityFresnel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionAmount", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_useRGBColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "useRGBColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_enableNoise", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "enableNoise", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], BackgroundMaterial.prototype, "_shadowOnly", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], BackgroundMaterial.prototype, "shadowOnly", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsImageProcessingConfiguration"])()
], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
return BackgroundMaterial;
}(_Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_8__["PushMaterial"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_12__["_TypeStore"].RegisteredTypes["BABYLON.BackgroundMaterial"] = BackgroundMaterial;
/***/ }),
/***/ "./Materials/Background/index.ts":
/*!***************************************!*\
!*** ./Materials/Background/index.ts ***!
\***************************************/
/*! exports provided: BackgroundMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _backgroundMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./backgroundMaterial */ "./Materials/Background/backgroundMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BackgroundMaterial", function() { return _backgroundMaterial__WEBPACK_IMPORTED_MODULE_0__["BackgroundMaterial"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/currentScreenBlock.ts":
/*!**********************************************************!*\
!*** ./Materials/Node/Blocks/Dual/currentScreenBlock.ts ***!
\**********************************************************/
/*! exports provided: CurrentScreenBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CurrentScreenBlock", function() { return CurrentScreenBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Textures/texture */ "./Materials/Textures/texture.ts");
/**
* Base block used as input for post process
*/
var CurrentScreenBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CurrentScreenBlock, _super);
/**
* Create a new CurrentScreenBlock
* @param name defines the block name
*/
function CurrentScreenBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment) || this;
_this._samplerName = "textureSampler";
/**
* Gets or sets a boolean indicating if content needs to be converted to gamma space
*/
_this.convertToGammaSpace = false;
/**
* Gets or sets a boolean indicating if content needs to be converted to linear space
*/
_this.convertToLinearSpace = false;
_this._isUnique = true;
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment);
_this.registerOutput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("r", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("g", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("b", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[0]._prioritizeVertex = true;
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
CurrentScreenBlock.prototype.getClassName = function () {
return "CurrentScreenBlock";
};
Object.defineProperty(CurrentScreenBlock.prototype, "uv", {
/**
* Gets the uv input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CurrentScreenBlock.prototype, "rgba", {
/**
* Gets the rgba output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CurrentScreenBlock.prototype, "rgb", {
/**
* Gets the rgb output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CurrentScreenBlock.prototype, "r", {
/**
* Gets the r output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CurrentScreenBlock.prototype, "g", {
/**
* Gets the g output component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CurrentScreenBlock.prototype, "b", {
/**
* Gets the b output component
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CurrentScreenBlock.prototype, "a", {
/**
* Gets the a output component
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
CurrentScreenBlock.prototype.initialize = function (state) {
state._excludeVariableName("textureSampler");
};
Object.defineProperty(CurrentScreenBlock.prototype, "target", {
get: function () {
// TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.
// But we need to detect uvs coming from fragment then
if (!this.uv.isConnected) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
}
if (this.uv.sourceBlock.isInput) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
}
var parent = this.uv.connectedPoint;
while (parent) {
if (parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment;
}
if (parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
}
if (parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral || parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment) {
var parentBlock = parent.ownerBlock;
parent = null;
for (var _i = 0, _a = parentBlock.inputs; _i < _a.length; _i++) {
var input = _a[_i];
if (input.connectedPoint) {
parent = input.connectedPoint;
break;
}
}
}
}
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
},
enumerable: false,
configurable: true
});
CurrentScreenBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);
defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);
};
CurrentScreenBlock.prototype.isReady = function () {
if (this.texture && !this.texture.isReadyOrNotBlocking()) {
return false;
}
return true;
};
CurrentScreenBlock.prototype._injectVertexCode = function (state) {
var uvInput = this.uv;
if (uvInput.connectedPoint.ownerBlock.isInput) {
var uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;
if (!uvInputOwnerBlock.isAttribute) {
state._emitUniformFromString(uvInput.associatedVariableName, "vec2");
}
}
this._mainUVName = "vMain" + uvInput.associatedVariableName;
state._emitVaryingFromString(this._mainUVName, "vec2");
state.compilationString += this._mainUVName + " = " + uvInput.associatedVariableName + ".xy;\r\n";
if (!this._outputs.some(function (o) { return o.isConnectedInVertexShader; })) {
return;
}
this._writeTextureRead(state, true);
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
this._writeOutput(state, output, output.name, true);
}
}
};
CurrentScreenBlock.prototype._writeTextureRead = function (state, vertexMode) {
if (vertexMode === void 0) { vertexMode = false; }
var uvInput = this.uv;
if (vertexMode) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
return;
}
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + uvInput.associatedVariableName + ");\r\n";
return;
}
if (this.uv.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + uvInput.associatedVariableName + ");\r\n";
return;
}
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._mainUVName + ");\r\n";
};
CurrentScreenBlock.prototype._writeOutput = function (state, output, swizzle, vertexMode) {
if (vertexMode === void 0) { vertexMode = false; }
if (vertexMode) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
return;
}
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + ";\r\n";
return;
}
if (this.uv.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + ";\r\n";
return;
}
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + ";\r\n";
state.compilationString += "#ifdef " + this._linearDefineName + "\r\n";
state.compilationString += output.associatedVariableName + " = toGammaSpace(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += "#ifdef " + this._gammaDefineName + "\r\n";
state.compilationString += output.associatedVariableName + " = toLinearSpace(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
};
CurrentScreenBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
state._emit2DSampler(this._samplerName);
state.sharedData.blockingBlocks.push(this);
state.sharedData.textureBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
}
if (state.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
// Vertex
this._injectVertexCode(state);
return;
}
// Fragment
if (!this._outputs.some(function (o) { return o.isConnectedInFragmentShader; })) {
return;
}
state._emit2DSampler(this._samplerName);
this._linearDefineName = state._getFreeDefineName("ISLINEAR");
this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
var comments = "//" + this.name;
state._emitFunctionFromInclude("helperFunctions", comments);
this._writeTextureRead(state);
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
this._writeOutput(state, output, output.name);
}
}
return this;
};
CurrentScreenBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.convertToGammaSpace = this.convertToGammaSpace;
serializationObject.convertToLinearSpace = this.convertToLinearSpace;
if (this.texture) {
serializationObject.texture = this.texture.serialize();
}
return serializationObject;
};
CurrentScreenBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.convertToGammaSpace = serializationObject.convertToGammaSpace;
this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
if (serializationObject.texture) {
rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
this.texture = _Textures_texture__WEBPACK_IMPORTED_MODULE_5__["Texture"].Parse(serializationObject.texture, scene, rootUrl);
}
};
return CurrentScreenBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.CurrentScreenBlock"] = CurrentScreenBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/fogBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/Dual/fogBlock.ts ***!
\************************************************/
/*! exports provided: FogBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return FogBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Shaders_ShadersInclude_fogFragmentDeclaration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/fogFragmentDeclaration */ "./Shaders/ShadersInclude/fogFragmentDeclaration.ts");
/**
* Block used to add support for scene fog
*/
var FogBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FogBlock, _super);
/**
* Create a new FogBlock
* @param name defines the block name
*/
function FogBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].VertexAndFragment, true) || this;
// Vertex
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("view", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex);
// Fragment
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("fogColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.input.acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this.fogColor.acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
FogBlock.prototype.getClassName = function () {
return "FogBlock";
};
Object.defineProperty(FogBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FogBlock.prototype, "view", {
/**
* Gets the view input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FogBlock.prototype, "input", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FogBlock.prototype, "fogColor", {
/**
* Gets the fog color input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FogBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
FogBlock.prototype.autoConfigure = function (material) {
if (!this.view.isConnected) {
var viewInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"].View; });
if (!viewInput) {
viewInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("view");
viewInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"].View);
}
viewInput.output.connectTo(this.view);
}
if (!this.fogColor.isConnected) {
var fogColorInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"].FogColor; });
if (!fogColorInput) {
fogColorInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("fogColor", undefined, _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
fogColorInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"].FogColor);
}
fogColorInput.output.connectTo(this.fogColor);
}
};
FogBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
var scene = mesh.getScene();
defines.setValue("FOG", nodeMaterial.fogEnabled && _materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].GetFogState(mesh, scene));
};
FogBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (!mesh) {
return;
}
var scene = mesh.getScene();
effect.setFloat4(this._fogParameters, scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
};
FogBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.blocksWithDefines.push(this);
state.sharedData.bindableBlocks.push(this);
state._emitFunctionFromInclude("fogFragmentDeclaration", "//" + this.name, {
removeUniforms: true,
removeVaryings: true,
removeIfDef: false,
replaceStrings: [{ search: /float CalcFogFactor\(\)/, replace: "float CalcFogFactor(vec3 vFogDistance, vec4 vFogInfos)" }]
});
var tempFogVariablename = state._getFreeVariableName("fog");
var color = this.input;
var fogColor = this.fogColor;
this._fogParameters = state._getFreeVariableName("fogParameters");
var output = this._outputs[0];
state._emitUniformFromString(this._fogParameters, "vec4");
state.compilationString += "#ifdef FOG\r\n";
state.compilationString += "float " + tempFogVariablename + " = CalcFogFactor(" + this._fogDistanceName + ", " + this._fogParameters + ");\r\n";
state.compilationString += this._declareOutput(output, state) + (" = " + tempFogVariablename + " * " + color.associatedVariableName + ".rgb + (1.0 - " + tempFogVariablename + ") * " + fogColor.associatedVariableName + ".rgb;\r\n");
state.compilationString += "#else\r\n" + this._declareOutput(output, state) + " = " + color.associatedVariableName + ".rgb;\r\n";
state.compilationString += "#endif\r\n";
}
else {
var worldPos = this.worldPosition;
var view = this.view;
this._fogDistanceName = state._getFreeVariableName("vFogDistance");
state._emitVaryingFromString(this._fogDistanceName, "vec3");
state.compilationString += this._fogDistanceName + " = (" + view.associatedVariableName + " * " + worldPos.associatedVariableName + ").xyz;\r\n";
}
return this;
};
return FogBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.FogBlock"] = FogBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/index.ts":
/*!*********************************************!*\
!*** ./Materials/Node/Blocks/Dual/index.ts ***!
\*********************************************/
/*! exports provided: FogBlock, LightBlock, TextureBlock, ReflectionTextureBlock, CurrentScreenBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _fogBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fogBlock */ "./Materials/Node/Blocks/Dual/fogBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _fogBlock__WEBPACK_IMPORTED_MODULE_0__["FogBlock"]; });
/* harmony import */ var _lightBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./lightBlock */ "./Materials/Node/Blocks/Dual/lightBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightBlock", function() { return _lightBlock__WEBPACK_IMPORTED_MODULE_1__["LightBlock"]; });
/* harmony import */ var _textureBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./textureBlock */ "./Materials/Node/Blocks/Dual/textureBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _textureBlock__WEBPACK_IMPORTED_MODULE_2__["TextureBlock"]; });
/* harmony import */ var _reflectionTextureBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./reflectionTextureBlock */ "./Materials/Node/Blocks/Dual/reflectionTextureBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionTextureBlock", function() { return _reflectionTextureBlock__WEBPACK_IMPORTED_MODULE_3__["ReflectionTextureBlock"]; });
/* harmony import */ var _currentScreenBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./currentScreenBlock */ "./Materials/Node/Blocks/Dual/currentScreenBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CurrentScreenBlock", function() { return _currentScreenBlock__WEBPACK_IMPORTED_MODULE_4__["CurrentScreenBlock"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/lightBlock.ts":
/*!**************************************************!*\
!*** ./Materials/Node/Blocks/Dual/lightBlock.ts ***!
\**************************************************/
/*! exports provided: LightBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightBlock", function() { return LightBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Shaders_ShadersInclude_lightFragmentDeclaration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/lightFragmentDeclaration */ "./Shaders/ShadersInclude/lightFragmentDeclaration.ts");
/* harmony import */ var _Shaders_ShadersInclude_lightUboDeclaration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/lightUboDeclaration */ "./Shaders/ShadersInclude/lightUboDeclaration.ts");
/* harmony import */ var _Shaders_ShadersInclude_lightFragment__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/lightFragment */ "./Shaders/ShadersInclude/lightFragment.ts");
/* harmony import */ var _Shaders_ShadersInclude_helperFunctions__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/helperFunctions */ "./Shaders/ShadersInclude/helperFunctions.ts");
/* harmony import */ var _Shaders_ShadersInclude_lightsFragmentFunctions__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/lightsFragmentFunctions */ "./Shaders/ShadersInclude/lightsFragmentFunctions.ts");
/* harmony import */ var _Shaders_ShadersInclude_shadowsFragmentFunctions__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/shadowsFragmentFunctions */ "./Shaders/ShadersInclude/shadowsFragmentFunctions.ts");
/* harmony import */ var _Shaders_ShadersInclude_shadowsVertex__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/shadowsVertex */ "./Shaders/ShadersInclude/shadowsVertex.ts");
/**
* Block used to add light in the fragment shader
*/
var LightBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LightBlock, _super);
/**
* Create a new LightBlock
* @param name defines the block name
*/
function LightBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].VertexAndFragment) || this;
_this._isUnique = true;
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("worldNormal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("cameraPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("glossiness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("glossPower", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("diffuseColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("specularColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("diffuseOutput", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("specularOutput", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("shadow", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
LightBlock.prototype.getClassName = function () {
return "LightBlock";
};
Object.defineProperty(LightBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "worldNormal", {
/**
* Gets the world normal input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "cameraPosition", {
/**
* Gets the camera (or eye) position component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "glossiness", {
/**
* Gets the glossiness component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "glossPower", {
/**
* Gets the glossinness power component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "diffuseColor", {
/**
* Gets the diffuse color component
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "specularColor", {
/**
* Gets the specular color component
*/
get: function () {
return this._inputs[6];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "diffuseOutput", {
/**
* Gets the diffuse output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "specularOutput", {
/**
* Gets the specular output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightBlock.prototype, "shadow", {
/**
* Gets the shadow output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
LightBlock.prototype.autoConfigure = function (material) {
if (!this.cameraPosition.isConnected) {
var cameraPositionInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].CameraPosition; });
if (!cameraPositionInput) {
cameraPositionInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("cameraPosition");
cameraPositionInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].CameraPosition);
}
cameraPositionInput.output.connectTo(this.cameraPosition);
}
};
LightBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (!defines._areLightsDirty) {
return;
}
var scene = mesh.getScene();
if (!this.light) {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);
}
else {
var state = {
needNormals: false,
needRebuild: false,
lightmapMode: false,
shadowEnabled: false,
specularEnabled: false
};
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);
if (state.needRebuild) {
defines.rebuild();
}
}
};
LightBlock.prototype.updateUniformsAndSamples = function (state, nodeMaterial, defines, uniformBuffers) {
for (var lightIndex = 0; lightIndex < nodeMaterial.maxSimultaneousLights; lightIndex++) {
if (!defines["LIGHT" + lightIndex]) {
break;
}
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareUniformsAndSamplersForLight(lightIndex, state.uniforms, state.samplers, defines["PROJECTEDLIGHTTEXTURE" + lightIndex], uniformBuffers);
}
};
LightBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (!mesh) {
return;
}
var scene = mesh.getScene();
if (!this.light) {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);
}
else {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindLight(this.light, this._lightId, scene, effect, true);
}
};
LightBlock.prototype._injectVertexCode = function (state) {
var worldPos = this.worldPosition;
var comments = "//" + this.name;
// Declaration
if (!this.light) { // Emit for all lights
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
repeatKey: "maxSimultaneousLights"
});
this._lightId = 0;
state.sharedData.dynamicUniformBlocks.push(this);
}
else {
this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1;
state.counters["lightCounter"] = this._lightId;
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
}, this._lightId.toString());
}
// Inject code in vertex
var worldPosVaryingName = "v_" + worldPos.associatedVariableName;
if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
state.compilationString += worldPosVaryingName + " = " + worldPos.associatedVariableName + ";\r\n";
}
if (this.light) {
state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
replaceStrings: [
{ search: /{X}/g, replace: this._lightId.toString() },
{ search: /worldPos/g, replace: worldPos.associatedVariableName }
]
});
}
else {
state.compilationString += "vec4 worldPos = " + worldPos.associatedVariableName + ";\r\n";
state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
repeatKey: "maxSimultaneousLights"
});
}
};
LightBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment) {
// Vertex
this._injectVertexCode(state);
return;
}
// Fragment
state.sharedData.bindableBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
var comments = "//" + this.name;
var worldPos = this.worldPosition;
state._emitFunctionFromInclude("helperFunctions", comments);
state._emitFunctionFromInclude("lightsFragmentFunctions", comments, {
replaceStrings: [
{ search: /vPositionW/g, replace: "v_" + worldPos.associatedVariableName + ".xyz" }
]
});
state._emitFunctionFromInclude("shadowsFragmentFunctions", comments, {
replaceStrings: [
{ search: /vPositionW/g, replace: "v_" + worldPos.associatedVariableName + ".xyz" }
]
});
if (!this.light) { // Emit for all lights
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
repeatKey: "maxSimultaneousLights"
});
}
else {
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
}, this._lightId.toString());
}
// Code
if (this._lightId === 0) {
if (state._registerTempVariable("viewDirectionW")) {
state.compilationString += "vec3 viewDirectionW = normalize(" + this.cameraPosition.associatedVariableName + " - " + ("v_" + worldPos.associatedVariableName) + ".xyz);\r\n";
}
state.compilationString += "lightingInfo info;\r\n";
state.compilationString += "float shadow = 1.;\r\n";
state.compilationString += "float glossiness = " + (this.glossiness.isConnected ? this.glossiness.associatedVariableName : "1.0") + " * " + (this.glossPower.isConnected ? this.glossPower.associatedVariableName : "1024.0") + ";\r\n";
state.compilationString += "vec3 diffuseBase = vec3(0., 0., 0.);\r\n";
state.compilationString += "vec3 specularBase = vec3(0., 0., 0.);\r\n";
state.compilationString += "vec3 normalW = " + this.worldNormal.associatedVariableName + ".xyz;\r\n";
}
if (this.light) {
state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
replaceStrings: [
{ search: /{X}/g, replace: this._lightId.toString() }
]
});
}
else {
state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
repeatKey: "maxSimultaneousLights"
});
}
var diffuseOutput = this.diffuseOutput;
var specularOutput = this.specularOutput;
state.compilationString += this._declareOutput(diffuseOutput, state) + (" = diffuseBase" + (this.diffuseColor.isConnected ? " * " + this.diffuseColor.associatedVariableName : "") + ";\r\n");
if (specularOutput.hasEndpoints) {
state.compilationString += this._declareOutput(specularOutput, state) + (" = specularBase" + (this.specularColor.isConnected ? " * " + this.specularColor.associatedVariableName : "") + ";\r\n");
}
if (this.shadow.hasEndpoints) {
state.compilationString += this._declareOutput(this.shadow, state) + " = shadow;\r\n";
}
return this;
};
LightBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
if (this.light) {
serializationObject.lightId = this.light.id;
}
return serializationObject;
};
LightBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
if (serializationObject.lightId) {
this.light = scene.getLightByID(serializationObject.lightId);
}
};
return LightBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.LightBlock"] = LightBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.ts":
/*!******************************************************************!*\
!*** ./Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.ts ***!
\******************************************************************/
/*! exports provided: ReflectionTextureBaseBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectionTextureBaseBlock", function() { return ReflectionTextureBaseBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Shaders_ShadersInclude_reflectionFunction__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/reflectionFunction */ "./Shaders/ShadersInclude/reflectionFunction.ts");
/* harmony import */ var _Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../Textures/texture */ "./Materials/Textures/texture.ts");
/**
* Base block used to read a reflection texture from a sampler
*/
var ReflectionTextureBaseBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReflectionTextureBaseBlock, _super);
/**
* Create a new ReflectionTextureBaseBlock
* @param name defines the block name
*/
function ReflectionTextureBaseBlock(name) {
return _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].VertexAndFragment) || this;
}
/**
* Gets the current class name
* @returns the class name
*/
ReflectionTextureBaseBlock.prototype.getClassName = function () {
return "ReflectionTextureBaseBlock";
};
ReflectionTextureBaseBlock.prototype._getTexture = function () {
return this.texture;
};
ReflectionTextureBaseBlock.prototype.autoConfigure = function (material) {
if (!this.position.isConnected) {
var positionInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "position"; });
if (!positionInput) {
positionInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__["InputBlock"]("position");
positionInput.setAsAttribute();
}
positionInput.output.connectTo(this.position);
}
if (!this.world.isConnected) {
var worldInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].World; });
if (!worldInput) {
worldInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__["InputBlock"]("world");
worldInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].World);
}
worldInput.output.connectTo(this.world);
}
if (!this.view.isConnected) {
var viewInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].View; });
if (!viewInput) {
viewInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__["InputBlock"]("view");
viewInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].View);
}
viewInput.output.connectTo(this.view);
}
};
ReflectionTextureBaseBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (!defines._areTexturesDirty) {
return;
}
var texture = this._getTexture();
if (!texture || !texture.getTextureMatrix) {
return;
}
defines.setValue(this._define3DName, texture.isCube, true);
defines.setValue(this._defineLocalCubicName, texture.boundingBoxSize ? true : false, true);
defines.setValue(this._defineExplicitName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EXPLICIT_MODE, true);
defines.setValue(this._defineSkyboxName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SKYBOX_MODE, true);
defines.setValue(this._defineCubicName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_CUBIC_MODE, true);
defines.setValue(this._defineSphericalName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_SPHERICAL_MODE, true);
defines.setValue(this._definePlanarName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PLANAR_MODE, true);
defines.setValue(this._defineProjectionName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_PROJECTION_MODE, true);
defines.setValue(this._defineEquirectangularName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_EQUIRECTANGULAR_MODE, true);
defines.setValue(this._defineEquirectangularFixedName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MODE, true);
defines.setValue(this._defineMirroredEquirectangularFixedName, texture.coordinatesMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_6__["Constants"].TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE, true);
};
ReflectionTextureBaseBlock.prototype.isReady = function () {
var texture = this._getTexture();
if (texture && !texture.isReadyOrNotBlocking()) {
return false;
}
return true;
};
ReflectionTextureBaseBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
var texture = this._getTexture();
if (!mesh || !texture) {
return;
}
effect.setMatrix(this._reflectionMatrixName, texture.getReflectionTextureMatrix());
if (texture.isCube) {
effect.setTexture(this._cubeSamplerName, texture);
}
else {
effect.setTexture(this._2DSamplerName, texture);
}
};
/**
* Gets the code to inject in the vertex shader
* @param state current state of the node material building
* @returns the shader code
*/
ReflectionTextureBaseBlock.prototype.handleVertexSide = function (state) {
this._define3DName = state._getFreeDefineName("REFLECTIONMAP_3D");
this._defineCubicName = state._getFreeDefineName("REFLECTIONMAP_CUBIC");
this._defineSphericalName = state._getFreeDefineName("REFLECTIONMAP_SPHERICAL");
this._definePlanarName = state._getFreeDefineName("REFLECTIONMAP_PLANAR");
this._defineProjectionName = state._getFreeDefineName("REFLECTIONMAP_PROJECTION");
this._defineExplicitName = state._getFreeDefineName("REFLECTIONMAP_EXPLICIT");
this._defineEquirectangularName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR");
this._defineLocalCubicName = state._getFreeDefineName("USE_LOCAL_REFLECTIONMAP_CUBIC");
this._defineMirroredEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
this._defineEquirectangularFixedName = state._getFreeDefineName("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
this._defineSkyboxName = state._getFreeDefineName("REFLECTIONMAP_SKYBOX");
this._defineOppositeZ = state._getFreeDefineName("REFLECTIONMAP_OPPOSITEZ");
this._reflectionMatrixName = state._getFreeVariableName("reflectionMatrix");
state._emitUniformFromString(this._reflectionMatrixName, "mat4");
var code = "";
var worldPosVaryingName = "v_" + this.worldPosition.associatedVariableName;
if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
code += worldPosVaryingName + " = " + this.worldPosition.associatedVariableName + ";\r\n";
}
this._positionUVWName = state._getFreeVariableName("positionUVW");
this._directionWName = state._getFreeVariableName("directionW");
if (state._emitVaryingFromString(this._positionUVWName, "vec3", this._defineSkyboxName)) {
code += "#ifdef " + this._defineSkyboxName + "\r\n";
code += this._positionUVWName + " = " + this.position.associatedVariableName + ".xyz;\r\n";
code += "#endif\r\n";
}
if (state._emitVaryingFromString(this._directionWName, "vec3", "defined(" + this._defineEquirectangularFixedName + ") || defined(" + this._defineMirroredEquirectangularFixedName + ")")) {
code += "#if defined(" + this._defineEquirectangularFixedName + ") || defined(" + this._defineMirroredEquirectangularFixedName + ")\r\n";
code += this._directionWName + " = normalize(vec3(" + this.world.associatedVariableName + " * vec4(" + this.position.associatedVariableName + ".xyz, 0.0)));\r\n";
code += "#endif\r\n";
}
return code;
};
/**
* Handles the inits for the fragment code path
* @param state node material build state
*/
ReflectionTextureBaseBlock.prototype.handleFragmentSideInits = function (state) {
state.sharedData.blockingBlocks.push(this);
state.sharedData.textureBlocks.push(this);
// Samplers
this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
state.samplers.push(this._cubeSamplerName);
this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
state.samplers.push(this._2DSamplerName);
state._samplerDeclaration += "#ifdef " + this._define3DName + "\r\n";
state._samplerDeclaration += "uniform samplerCube " + this._cubeSamplerName + ";\r\n";
state._samplerDeclaration += "#else\r\n";
state._samplerDeclaration += "uniform sampler2D " + this._2DSamplerName + ";\r\n";
state._samplerDeclaration += "#endif\r\n";
// Fragment
state.sharedData.blocksWithDefines.push(this);
state.sharedData.bindableBlocks.push(this);
var comments = "//" + this.name;
state._emitFunction("ReciprocalPI", "#define RECIPROCAL_PI2 0.15915494", "");
state._emitFunctionFromInclude("reflectionFunction", comments, {
replaceStrings: [
{ search: /vec3 computeReflectionCoords/g, replace: "void DUMMYFUNC" }
]
});
this._reflectionColorName = state._getFreeVariableName("reflectionColor");
this._reflectionVectorName = state._getFreeVariableName("reflectionUVW");
this._reflectionCoordsName = state._getFreeVariableName("reflectionCoords");
};
/**
* Generates the reflection coords code for the fragment code path
* @param worldNormalVarName name of the world normal variable
* @param worldPos name of the world position variable. If not provided, will use the world position connected to this block
* @param onlyReflectionVector if true, generates code only for the reflection vector computation, not for the reflection coordinates
* @returns the shader code
*/
ReflectionTextureBaseBlock.prototype.handleFragmentSideCodeReflectionCoords = function (worldNormalVarName, worldPos, onlyReflectionVector) {
if (onlyReflectionVector === void 0) { onlyReflectionVector = false; }
if (!worldPos) {
worldPos = "v_" + this.worldPosition.associatedVariableName;
}
var reflectionMatrix = this._reflectionMatrixName;
var direction = "normalize(" + this._directionWName + ")";
var positionUVW = "" + this._positionUVWName;
var vEyePosition = "" + this.cameraPosition.associatedVariableName;
var view = "" + this.view.associatedVariableName;
worldNormalVarName += ".xyz";
var code = "\n #ifdef " + this._defineMirroredEquirectangularFixedName + "\n vec3 " + this._reflectionVectorName + " = computeMirroredFixedEquirectangularCoords(" + worldPos + ", " + worldNormalVarName + ", " + direction + ");\n #endif\n\n #ifdef " + this._defineEquirectangularFixedName + "\n vec3 " + this._reflectionVectorName + " = computeFixedEquirectangularCoords(" + worldPos + ", " + worldNormalVarName + ", " + direction + ");\n #endif\n\n #ifdef " + this._defineEquirectangularName + "\n vec3 " + this._reflectionVectorName + " = computeEquirectangularCoords(" + worldPos + ", " + worldNormalVarName + ", " + vEyePosition + ".xyz, " + reflectionMatrix + ");\n #endif\n\n #ifdef " + this._defineSphericalName + "\n vec3 " + this._reflectionVectorName + " = computeSphericalCoords(" + worldPos + ", " + worldNormalVarName + ", " + view + ", " + reflectionMatrix + ");\n #endif\n\n #ifdef " + this._definePlanarName + "\n vec3 " + this._reflectionVectorName + " = computePlanarCoords(" + worldPos + ", " + worldNormalVarName + ", " + vEyePosition + ".xyz, " + reflectionMatrix + ");\n #endif\n\n #ifdef " + this._defineCubicName + "\n #ifdef " + this._defineLocalCubicName + "\n vec3 " + this._reflectionVectorName + " = computeCubicLocalCoords(" + worldPos + ", " + worldNormalVarName + ", " + vEyePosition + ".xyz, " + reflectionMatrix + ", vReflectionSize, vReflectionPosition);\n #else\n vec3 " + this._reflectionVectorName + " = computeCubicCoords(" + worldPos + ", " + worldNormalVarName + ", " + vEyePosition + ".xyz, " + reflectionMatrix + ");\n #endif\n #endif\n\n #ifdef " + this._defineProjectionName + "\n vec3 " + this._reflectionVectorName + " = computeProjectionCoords(" + worldPos + ", " + view + ", " + reflectionMatrix + ");\n #endif\n\n #ifdef " + this._defineSkyboxName + "\n vec3 " + this._reflectionVectorName + " = computeSkyBoxCoords(" + positionUVW + ", " + reflectionMatrix + ");\n #endif\n\n #ifdef " + this._defineExplicitName + "\n vec3 " + this._reflectionVectorName + " = vec3(0, 0, 0);\n #endif\n\n #ifdef " + this._defineOppositeZ + "\n " + this._reflectionVectorName + ".z *= -1.0;\n #endif\r\n";
if (!onlyReflectionVector) {
code += "\n #ifdef " + this._define3DName + "\n vec3 " + this._reflectionCoordsName + " = " + this._reflectionVectorName + ";\n #else\n vec2 " + this._reflectionCoordsName + " = " + this._reflectionVectorName + ".xy;\n #ifdef " + this._defineProjectionName + "\n " + this._reflectionCoordsName + " /= " + this._reflectionVectorName + ".z;\n #endif\n " + this._reflectionCoordsName + ".y = 1.0 - " + this._reflectionCoordsName + ".y;\n #endif\r\n";
}
return code;
};
/**
* Generates the reflection color code for the fragment code path
* @param lodVarName name of the lod variable
* @param swizzleLookupTexture swizzle to use for the final color variable
* @returns the shader code
*/
ReflectionTextureBaseBlock.prototype.handleFragmentSideCodeReflectionColor = function (lodVarName, swizzleLookupTexture) {
if (swizzleLookupTexture === void 0) { swizzleLookupTexture = ".rgb"; }
var colorType = "vec" + (swizzleLookupTexture.length === 0 ? "4" : (swizzleLookupTexture.length - 1));
var code = colorType + " " + this._reflectionColorName + ";\n #ifdef " + this._define3DName + "\r\n";
if (lodVarName) {
code += this._reflectionColorName + " = textureCubeLodEXT(" + this._cubeSamplerName + ", " + this._reflectionVectorName + ", " + lodVarName + ")" + swizzleLookupTexture + ";\r\n";
}
else {
code += this._reflectionColorName + " = textureCube(" + this._cubeSamplerName + ", " + this._reflectionVectorName + ")" + swizzleLookupTexture + ";\r\n";
}
code += "\n #else\r\n";
if (lodVarName) {
code += this._reflectionColorName + " = texture2DLodEXT(" + this._2DSamplerName + ", " + this._reflectionCoordsName + ", " + lodVarName + ")" + swizzleLookupTexture + ";\r\n";
}
else {
code += this._reflectionColorName + " = texture2D(" + this._2DSamplerName + ", " + this._reflectionCoordsName + ")" + swizzleLookupTexture + ";\r\n";
}
code += "#endif\r\n";
return code;
};
/**
* Generates the code corresponding to the connected output points
* @param state node material build state
* @param varName name of the variable to output
* @returns the shader code
*/
ReflectionTextureBaseBlock.prototype.writeOutputs = function (state, varName) {
var code = "";
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment) {
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
code += this._declareOutput(output, state) + " = " + varName + "." + output.name + ";\r\n";
}
}
}
return code;
};
ReflectionTextureBaseBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
return this;
};
ReflectionTextureBaseBlock.prototype._dumpPropertiesCode = function () {
if (!this.texture) {
return "";
}
var codeString;
if (this.texture.isCube) {
codeString = this._codeVariableName + ".texture = new BABYLON.CubeTexture(\"" + this.texture.name + "\");\r\n";
}
else {
codeString = this._codeVariableName + ".texture = new BABYLON.Texture(\"" + this.texture.name + "\");\r\n";
}
codeString += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + ";\r\n";
return codeString;
};
ReflectionTextureBaseBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
if (this.texture) {
serializationObject.texture = this.texture.serialize();
}
return serializationObject;
};
ReflectionTextureBaseBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
if (serializationObject.texture) {
rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
if (serializationObject.texture.isCube) {
this.texture = _Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_8__["CubeTexture"].Parse(serializationObject.texture, scene, rootUrl);
}
else {
this.texture = _Textures_texture__WEBPACK_IMPORTED_MODULE_9__["Texture"].Parse(serializationObject.texture, scene, rootUrl);
}
}
};
return ReflectionTextureBaseBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.ReflectionTextureBaseBlock"] = ReflectionTextureBaseBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/reflectionTextureBlock.ts":
/*!**************************************************************!*\
!*** ./Materials/Node/Blocks/Dual/reflectionTextureBlock.ts ***!
\**************************************************************/
/*! exports provided: ReflectionTextureBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectionTextureBlock", function() { return ReflectionTextureBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _reflectionTextureBaseBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./reflectionTextureBaseBlock */ "./Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.ts");
/**
* Block used to read a reflection texture from a sampler
*/
var ReflectionTextureBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReflectionTextureBlock, _super);
/**
* Create a new ReflectionTextureBlock
* @param name defines the block name
*/
function ReflectionTextureBlock(name) {
var _this = _super.call(this, name) || this;
_this.registerInput("position", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Vector3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("worldNormal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment); // Flagging as fragment as the normal can be changed by fragment code
_this.registerInput("world", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("cameraPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Vector3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("view", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Color4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("r", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("g", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("b", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Vector4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ReflectionTextureBlock.prototype.getClassName = function () {
return "ReflectionTextureBlock";
};
Object.defineProperty(ReflectionTextureBlock.prototype, "position", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "worldNormal", {
/**
* Gets the world normal input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "world", {
/**
* Gets the world input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "cameraPosition", {
/**
* Gets the camera (or eye) position component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "view", {
/**
* Gets the view input component
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "rgb", {
/**
* Gets the rgb output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "rgba", {
/**
* Gets the rgba output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "r", {
/**
* Gets the r output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "g", {
/**
* Gets the g output component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "b", {
/**
* Gets the b output component
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionTextureBlock.prototype, "a", {
/**
* Gets the a output component
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
ReflectionTextureBlock.prototype.autoConfigure = function (material) {
_super.prototype.autoConfigure.call(this, material);
if (!this.cameraPosition.isConnected) {
var cameraPositionInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].CameraPosition; });
if (!cameraPositionInput) {
cameraPositionInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__["InputBlock"]("cameraPosition");
cameraPositionInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].CameraPosition);
}
cameraPositionInput.output.connectTo(this.cameraPosition);
}
};
ReflectionTextureBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (!this.texture) {
state.compilationString += this.writeOutputs(state, "vec3(0.)");
return this;
}
if (state.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment) {
state.compilationString += this.handleVertexSide(state);
return this;
}
this.handleFragmentSideInits(state);
var normalWUnit = state._getFreeVariableName("normalWUnit");
state.compilationString += "vec4 " + normalWUnit + " = normalize(" + this.worldNormal.associatedVariableName + ");\r\n";
state.compilationString += this.handleFragmentSideCodeReflectionCoords(normalWUnit);
state.compilationString += this.handleFragmentSideCodeReflectionColor(undefined, "");
state.compilationString += this.writeOutputs(state, this._reflectionColorName);
return this;
};
return ReflectionTextureBlock;
}(_reflectionTextureBaseBlock__WEBPACK_IMPORTED_MODULE_6__["ReflectionTextureBaseBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.ReflectionTextureBlock"] = ReflectionTextureBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Dual/textureBlock.ts":
/*!****************************************************!*\
!*** ./Materials/Node/Blocks/Dual/textureBlock.ts ***!
\****************************************************/
/*! exports provided: TextureBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return TextureBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _nodeMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../nodeMaterial */ "./Materials/Node/nodeMaterial.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../Enums/nodeMaterialModes */ "./Materials/Node/Enums/nodeMaterialModes.ts");
/* harmony import */ var _Shaders_ShadersInclude_helperFunctions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/helperFunctions */ "./Shaders/ShadersInclude/helperFunctions.ts");
/**
* Block used to read a texture from a sampler
*/
var TextureBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TextureBlock, _super);
/**
* Create a new TextureBlock
* @param name defines the block name
*/
function TextureBlock(name, fragmentOnly) {
if (fragmentOnly === void 0) { fragmentOnly = false; }
var _this = _super.call(this, name, fragmentOnly ? _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment : _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment) || this;
/**
* Gets or sets a boolean indicating if content needs to be converted to gamma space
*/
_this.convertToGammaSpace = false;
/**
* Gets or sets a boolean indicating if content needs to be converted to linear space
*/
_this.convertToLinearSpace = false;
_this._fragmentOnly = fragmentOnly;
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment);
_this.registerOutput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("r", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("g", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("b", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[0]._prioritizeVertex = !fragmentOnly;
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
TextureBlock.prototype.getClassName = function () {
return "TextureBlock";
};
Object.defineProperty(TextureBlock.prototype, "uv", {
/**
* Gets the uv input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "rgba", {
/**
* Gets the rgba output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "rgb", {
/**
* Gets the rgb output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "r", {
/**
* Gets the r output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "g", {
/**
* Gets the g output component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "b", {
/**
* Gets the b output component
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "a", {
/**
* Gets the a output component
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TextureBlock.prototype, "target", {
get: function () {
if (this._fragmentOnly) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment;
}
// TextureBlock has a special optimizations for uvs that come from the vertex shaders as they can be packed into a single varyings.
// But we need to detect uvs coming from fragment then
if (!this.uv.isConnected) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
}
if (this.uv.sourceBlock.isInput) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
}
var parent = this.uv.connectedPoint;
while (parent) {
if (parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment;
}
if (parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
}
if (parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral || parent.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment) {
var parentBlock = parent.ownerBlock;
parent = null;
for (var _i = 0, _a = parentBlock.inputs; _i < _a.length; _i++) {
var input = _a[_i];
if (input.connectedPoint) {
parent = input.connectedPoint;
break;
}
}
}
}
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment;
},
enumerable: false,
configurable: true
});
TextureBlock.prototype.autoConfigure = function (material) {
if (!this.uv.isConnected) {
if (material.mode === _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialModes"].PostProcess) {
var uvInput = material.getBlockByPredicate(function (b) { return b.name === "uv"; });
if (uvInput) {
uvInput.connectTo(this);
}
}
else {
var attributeName_1 = material.mode === _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialModes"].Particle ? "particle_uv" : "uv";
var uvInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === attributeName_1; });
if (!uvInput) {
uvInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("uv");
uvInput.setAsAttribute(attributeName_1);
}
uvInput.output.connectTo(this.uv);
}
}
};
TextureBlock.prototype.initializeDefines = function (mesh, nodeMaterial, defines, useInstances) {
if (useInstances === void 0) { useInstances = false; }
if (!defines._areTexturesDirty) {
return;
}
defines.setValue(this._mainUVDefineName, false);
};
TextureBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (!defines._areTexturesDirty) {
return;
}
if (!this.texture || !this.texture.getTextureMatrix) {
defines.setValue(this._defineName, false);
defines.setValue(this._mainUVDefineName, true);
return;
}
defines.setValue(this._linearDefineName, this.convertToGammaSpace);
defines.setValue(this._gammaDefineName, this.convertToLinearSpace);
if (this._isMixed) {
if (!this.texture.getTextureMatrix().isIdentityAs3x2()) {
defines.setValue(this._defineName, true);
}
else {
defines.setValue(this._defineName, false);
defines.setValue(this._mainUVDefineName, true);
}
}
};
TextureBlock.prototype.isReady = function () {
if (this.texture && !this.texture.isReadyOrNotBlocking()) {
return false;
}
return true;
};
TextureBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (!this.texture) {
return;
}
if (this._isMixed) {
effect.setFloat(this._textureInfoName, this.texture.level);
effect.setMatrix(this._textureTransformName, this.texture.getTextureMatrix());
}
effect.setTexture(this._samplerName, this.texture);
};
Object.defineProperty(TextureBlock.prototype, "_isMixed", {
get: function () {
return this.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment;
},
enumerable: false,
configurable: true
});
TextureBlock.prototype._injectVertexCode = function (state) {
var uvInput = this.uv;
// Inject code in vertex
this._defineName = state._getFreeDefineName("UVTRANSFORM");
this._mainUVDefineName = "VMAIN" + uvInput.associatedVariableName.toUpperCase();
if (uvInput.connectedPoint.ownerBlock.isInput) {
var uvInputOwnerBlock = uvInput.connectedPoint.ownerBlock;
if (!uvInputOwnerBlock.isAttribute) {
state._emitUniformFromString(uvInput.associatedVariableName, "vec2");
}
}
this._mainUVName = "vMain" + uvInput.associatedVariableName;
this._transformedUVName = state._getFreeVariableName("transformedUV");
this._textureTransformName = state._getFreeVariableName("textureTransform");
this._textureInfoName = state._getFreeVariableName("textureInfoName");
state._emitVaryingFromString(this._transformedUVName, "vec2", this._defineName);
state._emitVaryingFromString(this._mainUVName, "vec2", this._mainUVDefineName);
state._emitUniformFromString(this._textureTransformName, "mat4", this._defineName);
state.compilationString += "#ifdef " + this._defineName + "\r\n";
state.compilationString += this._transformedUVName + " = vec2(" + this._textureTransformName + " * vec4(" + uvInput.associatedVariableName + ".xy, 1.0, 0.0));\r\n";
state.compilationString += "#elif defined(" + this._mainUVDefineName + ")\r\n";
state.compilationString += this._mainUVName + " = " + uvInput.associatedVariableName + ".xy;\r\n";
state.compilationString += "#endif\r\n";
if (!this._outputs.some(function (o) { return o.isConnectedInVertexShader; })) {
return;
}
this._writeTextureRead(state, true);
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
this._writeOutput(state, output, output.name, true);
}
}
};
TextureBlock.prototype._writeTextureRead = function (state, vertexMode) {
if (vertexMode === void 0) { vertexMode = false; }
var uvInput = this.uv;
if (vertexMode) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
return;
}
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + uvInput.associatedVariableName + ");\r\n";
return;
}
if (this.uv.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + uvInput.associatedVariableName + ");\r\n";
return;
}
state.compilationString += "#ifdef " + this._defineName + "\r\n";
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._transformedUVName + ");\r\n";
state.compilationString += "#elif defined(" + this._mainUVDefineName + ")\r\n";
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this._mainUVName + ");\r\n";
state.compilationString += "#endif\r\n";
};
TextureBlock.prototype._writeOutput = function (state, output, swizzle, vertexMode) {
if (vertexMode === void 0) { vertexMode = false; }
if (vertexMode) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
return;
}
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + ";\r\n";
return;
}
if (this.uv.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + ";\r\n";
return;
}
var complement = " * " + this._textureInfoName;
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + complement + ";\r\n";
if (swizzle !== 'a') { // no conversion if the output is "a" (alpha)
state.compilationString += "#ifdef " + this._linearDefineName + "\r\n";
state.compilationString += output.associatedVariableName + " = toGammaSpace(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += "#ifdef " + this._gammaDefineName + "\r\n";
state.compilationString += output.associatedVariableName + " = toLinearSpace(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
}
};
TextureBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex || this._fragmentOnly) {
this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
}
if (!this._isMixed && state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment || this._isMixed && state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
this._samplerName = state._getFreeVariableName(this.name + "Sampler");
state._emit2DSampler(this._samplerName);
// Declarations
state.sharedData.blockingBlocks.push(this);
state.sharedData.textureBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
state.sharedData.bindableBlocks.push(this);
}
if (state.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
// Vertex
this._injectVertexCode(state);
return;
}
// Fragment
if (!this._outputs.some(function (o) { return o.isConnectedInFragmentShader; })) {
return;
}
if (this._isMixed) {
// Reexport the sampler
state._emit2DSampler(this._samplerName);
}
this._linearDefineName = state._getFreeDefineName("ISLINEAR");
this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
var comments = "//" + this.name;
state._emitFunctionFromInclude("helperFunctions", comments);
if (this._isMixed) {
state._emitUniformFromString(this._textureInfoName, "float");
}
this._writeTextureRead(state);
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
this._writeOutput(state, output, output.name);
}
}
return this;
};
TextureBlock.prototype._dumpPropertiesCode = function () {
if (!this.texture) {
return "";
}
var codeString = this._codeVariableName + ".texture = new BABYLON.Texture(\"" + this.texture.name + "\", null);\r\n";
codeString += this._codeVariableName + ".texture.wrapU = " + this.texture.wrapU + ";\r\n";
codeString += this._codeVariableName + ".texture.wrapV = " + this.texture.wrapV + ";\r\n";
codeString += this._codeVariableName + ".texture.uAng = " + this.texture.uAng + ";\r\n";
codeString += this._codeVariableName + ".texture.vAng = " + this.texture.vAng + ";\r\n";
codeString += this._codeVariableName + ".texture.wAng = " + this.texture.wAng + ";\r\n";
codeString += this._codeVariableName + ".texture.uOffset = " + this.texture.uOffset + ";\r\n";
codeString += this._codeVariableName + ".texture.vOffset = " + this.texture.vOffset + ";\r\n";
codeString += this._codeVariableName + ".texture.uScale = " + this.texture.uScale + ";\r\n";
codeString += this._codeVariableName + ".texture.vScale = " + this.texture.vScale + ";\r\n";
codeString += this._codeVariableName + ".convertToGammaSpace = " + this.convertToGammaSpace + ";\r\n";
codeString += this._codeVariableName + ".convertToLinearSpace = " + this.convertToLinearSpace + ";\r\n";
return codeString;
};
TextureBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.convertToGammaSpace = this.convertToGammaSpace;
serializationObject.convertToLinearSpace = this.convertToLinearSpace;
serializationObject.fragmentOnly = this._fragmentOnly;
if (this.texture) {
serializationObject.texture = this.texture.serialize();
}
return serializationObject;
};
TextureBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.convertToGammaSpace = serializationObject.convertToGammaSpace;
this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
this._fragmentOnly = !!serializationObject.fragmentOnly;
if (serializationObject.texture && !_nodeMaterial__WEBPACK_IMPORTED_MODULE_4__["NodeMaterial"].IgnoreTexturesAtLoadTime) {
rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
this.texture = _Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].Parse(serializationObject.texture, scene, rootUrl);
}
};
return TextureBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__["_TypeStore"].RegisteredTypes["BABYLON.TextureBlock"] = TextureBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/derivativeBlock.ts":
/*!***********************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/derivativeBlock.ts ***!
\***********************************************************/
/*! exports provided: DerivativeBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DerivativeBlock", function() { return DerivativeBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the derivative value on x and y of a given input
*/
var DerivativeBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DerivativeBlock, _super);
/**
* Create a new DerivativeBlock
* @param name defines the block name
*/
function DerivativeBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect, false);
_this.registerOutput("dx", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this.registerOutput("dy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._outputs[1]._typeConnectionSource = _this._inputs[0];
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
DerivativeBlock.prototype.getClassName = function () {
return "DerivativeBlock";
};
Object.defineProperty(DerivativeBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DerivativeBlock.prototype, "dx", {
/**
* Gets the derivative output on x
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DerivativeBlock.prototype, "dy", {
/**
* Gets the derivative output on y
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
DerivativeBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var dx = this._outputs[0];
var dy = this._outputs[1];
state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
if (dx.hasEndpoints) {
state.compilationString += this._declareOutput(dx, state) + (" = dFdx(" + this.input.associatedVariableName + ");\r\n");
}
if (dy.hasEndpoints) {
state.compilationString += this._declareOutput(dy, state) + (" = dFdy(" + this.input.associatedVariableName + ");\r\n");
}
return this;
};
return DerivativeBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.DerivativeBlock"] = DerivativeBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/discardBlock.ts":
/*!********************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/discardBlock.ts ***!
\********************************************************/
/*! exports provided: DiscardBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DiscardBlock", function() { return DiscardBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to discard a pixel if a value is smaller than a cutoff
*/
var DiscardBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DiscardBlock, _super);
/**
* Create a new DiscardBlock
* @param name defines the block name
*/
function DiscardBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment, true) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("cutoff", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
DiscardBlock.prototype.getClassName = function () {
return "DiscardBlock";
};
Object.defineProperty(DiscardBlock.prototype, "value", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DiscardBlock.prototype, "cutoff", {
/**
* Gets the cutoff input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
DiscardBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
state.sharedData.hints.needAlphaTesting = true;
state.compilationString += "if (" + this.value.associatedVariableName + " < " + this.cutoff.associatedVariableName + ") discard;\r\n";
return this;
};
return DiscardBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.DiscardBlock"] = DiscardBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/fragCoordBlock.ts":
/*!**********************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/fragCoordBlock.ts ***!
\**********************************************************/
/*! exports provided: FragCoordBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragCoordBlock", function() { return FragCoordBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to make gl_FragCoord available
*/
var FragCoordBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FragCoordBlock, _super);
/**
* Creates a new FragCoordBlock
* @param name defines the block name
*/
function FragCoordBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this.registerOutput("xy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("xyz", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("xyzw", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("x", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("y", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("z", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("w", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
FragCoordBlock.prototype.getClassName = function () {
return "FragCoordBlock";
};
Object.defineProperty(FragCoordBlock.prototype, "xy", {
/**
* Gets the xy component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragCoordBlock.prototype, "xyz", {
/**
* Gets the xyz component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragCoordBlock.prototype, "xyzw", {
/**
* Gets the xyzw component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragCoordBlock.prototype, "x", {
/**
* Gets the x component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragCoordBlock.prototype, "y", {
/**
* Gets the y component
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragCoordBlock.prototype, "z", {
/**
* Gets the z component
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragCoordBlock.prototype, "output", {
/**
* Gets the w component
*/
get: function () {
return this._outputs[6];
},
enumerable: false,
configurable: true
});
FragCoordBlock.prototype.writeOutputs = function (state) {
var code = "";
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
code += this._declareOutput(output, state) + " = gl_FragCoord." + output.name + ";\r\n";
}
}
return code;
};
FragCoordBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
throw "FragCoordBlock must only be used in a fragment shader";
}
state.compilationString += this.writeOutputs(state);
return this;
};
return FragCoordBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.FragCoordBlock"] = FragCoordBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts":
/*!***************************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts ***!
\***************************************************************/
/*! exports provided: FragmentOutputBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return FragmentOutputBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to output the final color
*/
var FragmentOutputBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FragmentOutputBlock, _super);
/**
* Create a new FragmentOutputBlock
* @param name defines the block name
*/
function FragmentOutputBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment, true) || this;
_this.registerInput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, true);
_this.registerInput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true);
_this.registerInput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.rgb.acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
FragmentOutputBlock.prototype.getClassName = function () {
return "FragmentOutputBlock";
};
Object.defineProperty(FragmentOutputBlock.prototype, "rgba", {
/**
* Gets the rgba input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragmentOutputBlock.prototype, "rgb", {
/**
* Gets the rgb input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FragmentOutputBlock.prototype, "a", {
/**
* Gets the a input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
FragmentOutputBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var rgba = this.rgba;
var rgb = this.rgb;
var a = this.a;
state.sharedData.hints.needAlphaBlending = rgba.isConnected || a.isConnected;
if (rgba.connectedPoint) {
if (a.isConnected) {
state.compilationString += "gl_FragColor = vec4(" + rgba.associatedVariableName + ".rgb, " + a.associatedVariableName + ");\r\n";
}
else {
state.compilationString += "gl_FragColor = " + rgba.associatedVariableName + ";\r\n";
}
}
else if (rgb.connectedPoint) {
var aValue = "1.0";
if (a.connectedPoint) {
aValue = a.associatedVariableName;
}
if (rgb.connectedPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float) {
state.compilationString += "gl_FragColor = vec4(" + rgb.associatedVariableName + ", " + rgb.associatedVariableName + ", " + rgb.associatedVariableName + ", " + aValue + ");\r\n";
}
else {
state.compilationString += "gl_FragColor = vec4(" + rgb.associatedVariableName + ", " + aValue + ");\r\n";
}
}
else {
state.sharedData.checks.notConnectedNonOptionalInputs.push(rgba);
}
return this;
};
return FragmentOutputBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.FragmentOutputBlock"] = FragmentOutputBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/frontFacingBlock.ts":
/*!************************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/frontFacingBlock.ts ***!
\************************************************************/
/*! exports provided: FrontFacingBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FrontFacingBlock", function() { return FrontFacingBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to test if the fragment shader is front facing
*/
var FrontFacingBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FrontFacingBlock, _super);
/**
* Creates a new FrontFacingBlock
* @param name defines the block name
*/
function FrontFacingBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
FrontFacingBlock.prototype.getClassName = function () {
return "FrontFacingBlock";
};
Object.defineProperty(FrontFacingBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
FrontFacingBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
throw "FrontFacingBlock must only be used in a fragment shader";
}
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + " = gl_FrontFacing ? 1.0 : 0.0;\r\n";
return this;
};
return FrontFacingBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.FrontFacingBlock"] = FrontFacingBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/imageProcessingBlock.ts":
/*!****************************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/imageProcessingBlock.ts ***!
\****************************************************************/
/*! exports provided: ImageProcessingBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return ImageProcessingBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Shaders_ShadersInclude_helperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/helperFunctions */ "./Shaders/ShadersInclude/helperFunctions.ts");
/* harmony import */ var _Shaders_ShadersInclude_imageProcessingDeclaration__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/imageProcessingDeclaration */ "./Shaders/ShadersInclude/imageProcessingDeclaration.ts");
/* harmony import */ var _Shaders_ShadersInclude_imageProcessingFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/imageProcessingFunctions */ "./Shaders/ShadersInclude/imageProcessingFunctions.ts");
/**
* Block used to add image processing support to fragment shader
*/
var ImageProcessingBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ImageProcessingBlock, _super);
/**
* Create a new ImageProcessingBlock
* @param name defines the block name
*/
function ImageProcessingBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this.registerInput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ImageProcessingBlock.prototype.getClassName = function () {
return "ImageProcessingBlock";
};
Object.defineProperty(ImageProcessingBlock.prototype, "color", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ImageProcessingBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
ImageProcessingBlock.prototype.initialize = function (state) {
state._excludeVariableName("exposureLinear");
state._excludeVariableName("contrast");
state._excludeVariableName("vInverseScreenSize");
state._excludeVariableName("vignetteSettings1");
state._excludeVariableName("vignetteSettings2");
state._excludeVariableName("vCameraColorCurveNegative");
state._excludeVariableName("vCameraColorCurveNeutral");
state._excludeVariableName("vCameraColorCurvePositive");
state._excludeVariableName("txColorTransform");
state._excludeVariableName("colorTransformSettings");
};
ImageProcessingBlock.prototype.isReady = function (mesh, nodeMaterial, defines) {
if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {
if (!nodeMaterial.imageProcessingConfiguration.isReady()) {
return false;
}
}
return true;
};
ImageProcessingBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (defines._areImageProcessingDirty && nodeMaterial.imageProcessingConfiguration) {
nodeMaterial.imageProcessingConfiguration.prepareDefines(defines);
}
};
ImageProcessingBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (!mesh) {
return;
}
if (!nodeMaterial.imageProcessingConfiguration) {
return;
}
nodeMaterial.imageProcessingConfiguration.bind(effect);
};
ImageProcessingBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
// Register for defines
state.sharedData.blocksWithDefines.push(this);
// Register for blocking
state.sharedData.blockingBlocks.push(this);
// Register for binding
state.sharedData.bindableBlocks.push(this);
// Uniforms
state.uniforms.push("exposureLinear");
state.uniforms.push("contrast");
state.uniforms.push("vInverseScreenSize");
state.uniforms.push("vignetteSettings1");
state.uniforms.push("vignetteSettings2");
state.uniforms.push("vCameraColorCurveNegative");
state.uniforms.push("vCameraColorCurveNeutral");
state.uniforms.push("vCameraColorCurvePositive");
state.uniforms.push("txColorTransform");
state.uniforms.push("colorTransformSettings");
// Emit code
var color = this.color;
var output = this._outputs[0];
var comments = "//" + this.name;
state._emitFunctionFromInclude("helperFunctions", comments);
state._emitFunctionFromInclude("imageProcessingDeclaration", comments);
state._emitFunctionFromInclude("imageProcessingFunctions", comments);
if (color.connectedPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4 || (color.connectedPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4)) {
state.compilationString += this._declareOutput(output, state) + " = " + color.associatedVariableName + ";\r\n";
}
else {
state.compilationString += this._declareOutput(output, state) + " = vec4(" + color.associatedVariableName + ", 1.0);\r\n";
}
state.compilationString += "#ifdef IMAGEPROCESSINGPOSTPROCESS\r\n";
state.compilationString += output.associatedVariableName + ".rgb = toLinearSpace(" + color.associatedVariableName + ".rgb);\r\n";
state.compilationString += "#else\r\n";
state.compilationString += "#ifdef IMAGEPROCESSING\r\n";
state.compilationString += output.associatedVariableName + ".rgb = toLinearSpace(" + color.associatedVariableName + ".rgb);\r\n";
state.compilationString += output.associatedVariableName + " = applyImageProcessing(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += "#endif\r\n";
return this;
};
return ImageProcessingBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ImageProcessingBlock"] = ImageProcessingBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/index.ts":
/*!*************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/index.ts ***!
\*************************************************/
/*! exports provided: FragmentOutputBlock, ImageProcessingBlock, PerturbNormalBlock, DiscardBlock, FrontFacingBlock, DerivativeBlock, FragCoordBlock, ScreenSizeBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./fragmentOutputBlock */ "./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_0__["FragmentOutputBlock"]; });
/* harmony import */ var _imageProcessingBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./imageProcessingBlock */ "./Materials/Node/Blocks/Fragment/imageProcessingBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _imageProcessingBlock__WEBPACK_IMPORTED_MODULE_1__["ImageProcessingBlock"]; });
/* harmony import */ var _perturbNormalBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./perturbNormalBlock */ "./Materials/Node/Blocks/Fragment/perturbNormalBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerturbNormalBlock", function() { return _perturbNormalBlock__WEBPACK_IMPORTED_MODULE_2__["PerturbNormalBlock"]; });
/* harmony import */ var _discardBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./discardBlock */ "./Materials/Node/Blocks/Fragment/discardBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscardBlock", function() { return _discardBlock__WEBPACK_IMPORTED_MODULE_3__["DiscardBlock"]; });
/* harmony import */ var _frontFacingBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./frontFacingBlock */ "./Materials/Node/Blocks/Fragment/frontFacingBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FrontFacingBlock", function() { return _frontFacingBlock__WEBPACK_IMPORTED_MODULE_4__["FrontFacingBlock"]; });
/* harmony import */ var _derivativeBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./derivativeBlock */ "./Materials/Node/Blocks/Fragment/derivativeBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DerivativeBlock", function() { return _derivativeBlock__WEBPACK_IMPORTED_MODULE_5__["DerivativeBlock"]; });
/* harmony import */ var _fragCoordBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./fragCoordBlock */ "./Materials/Node/Blocks/Fragment/fragCoordBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragCoordBlock", function() { return _fragCoordBlock__WEBPACK_IMPORTED_MODULE_6__["FragCoordBlock"]; });
/* harmony import */ var _screenSizeBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./screenSizeBlock */ "./Materials/Node/Blocks/Fragment/screenSizeBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenSizeBlock", function() { return _screenSizeBlock__WEBPACK_IMPORTED_MODULE_7__["ScreenSizeBlock"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/perturbNormalBlock.ts":
/*!**************************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/perturbNormalBlock.ts ***!
\**************************************************************/
/*! exports provided: PerturbNormalBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PerturbNormalBlock", function() { return PerturbNormalBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _Shaders_ShadersInclude_bumpFragmentMainFunctions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/bumpFragmentMainFunctions */ "./Shaders/ShadersInclude/bumpFragmentMainFunctions.ts");
/* harmony import */ var _Shaders_ShadersInclude_bumpFragmentFunctions__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/bumpFragmentFunctions */ "./Shaders/ShadersInclude/bumpFragmentFunctions.ts");
/* harmony import */ var _Shaders_ShadersInclude_bumpFragment__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/bumpFragment */ "./Shaders/ShadersInclude/bumpFragment.ts");
/**
* Block used to pertub normals based on a normal map
*/
var PerturbNormalBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PerturbNormalBlock, _super);
/**
* Create a new PerturbNormalBlock
* @param name defines the block name
*/
function PerturbNormalBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this._tangentSpaceParameterName = "";
/** Gets or sets a boolean indicating that normal should be inverted on X axis */
_this.invertX = false;
/** Gets or sets a boolean indicating that normal should be inverted on Y axis */
_this.invertY = false;
// Vertex
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false);
_this.registerInput("worldNormal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false);
_this.registerInput("worldTangent", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true);
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, false);
_this.registerInput("normalMapColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, false);
_this.registerInput("strength", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, false);
// Fragment
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
PerturbNormalBlock.prototype.getClassName = function () {
return "PerturbNormalBlock";
};
Object.defineProperty(PerturbNormalBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PerturbNormalBlock.prototype, "worldNormal", {
/**
* Gets the world normal input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PerturbNormalBlock.prototype, "worldTangent", {
/**
* Gets the world tangent input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PerturbNormalBlock.prototype, "uv", {
/**
* Gets the uv input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PerturbNormalBlock.prototype, "normalMapColor", {
/**
* Gets the normal map color input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PerturbNormalBlock.prototype, "strength", {
/**
* Gets the strength input component
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PerturbNormalBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
PerturbNormalBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
defines.setValue("BUMP", true);
};
PerturbNormalBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (nodeMaterial.getScene()._mirroredCameraPosition) {
effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? 1.0 : -1.0, this.invertY ? 1.0 : -1.0);
}
else {
effect.setFloat2(this._tangentSpaceParameterName, this.invertX ? -1.0 : 1.0, this.invertY ? -1.0 : 1.0);
}
};
PerturbNormalBlock.prototype.autoConfigure = function (material) {
if (!this.uv.isConnected) {
var uvInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "uv"; });
if (!uvInput) {
uvInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("uv");
uvInput.setAsAttribute();
}
uvInput.output.connectTo(this.uv);
}
if (!this.strength.isConnected) {
var strengthInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("strength");
strengthInput.value = 1.0;
strengthInput.output.connectTo(this.strength);
}
};
PerturbNormalBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var comments = "//" + this.name;
var uv = this.uv;
var worldPosition = this.worldPosition;
var worldNormal = this.worldNormal;
var worldTangent = this.worldTangent;
state.sharedData.blocksWithDefines.push(this);
state.sharedData.bindableBlocks.push(this);
this._tangentSpaceParameterName = state._getFreeDefineName("tangentSpaceParameter");
state._emitUniformFromString(this._tangentSpaceParameterName, "vec2");
var replaceForBumpInfos = this.strength.isConnectedToInputBlock && this.strength.connectInputBlock.isConstant ? "" + state._emitFloat(1.0 / this.strength.connectInputBlock.value) : "1.0 / " + this.strength.associatedVariableName;
state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
var tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" };
if (worldTangent.isConnected) {
state.compilationString += "vec3 tbnNormal = normalize(" + worldNormal.associatedVariableName + ".xyz);\r\n";
state.compilationString += "vec3 tbnTangent = normalize(" + worldTangent.associatedVariableName + ".xyz);\r\n";
state.compilationString += "vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r\n";
state.compilationString += "mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n";
}
state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, {
replaceStrings: [
tangentReplaceString,
]
});
state._emitFunctionFromInclude("bumpFragmentFunctions", comments, {
replaceStrings: [
{ search: /vBumpInfos.y/g, replace: replaceForBumpInfos },
{ search: /vTangentSpaceParams/g, replace: this._tangentSpaceParameterName },
{ search: /vPositionW/g, replace: worldPosition.associatedVariableName + ".xyz" },
]
});
state.compilationString += this._declareOutput(this.output, state) + " = vec4(0.);\r\n";
state.compilationString += state._emitCodeFromInclude("bumpFragment", comments, {
replaceStrings: [
{ search: /perturbNormal\(TBN,vBumpUV\+uvOffset\)/g, replace: "perturbNormal(TBN, " + this.normalMapColor.associatedVariableName + ")" },
{ search: /vBumpInfos.y/g, replace: replaceForBumpInfos },
{ search: /vBumpUV/g, replace: uv.associatedVariableName },
{ search: /vPositionW/g, replace: worldPosition.associatedVariableName + ".xyz" },
{ search: /normalW=/g, replace: this.output.associatedVariableName + ".xyz = " },
{ search: /mat3\(normalMatrix\)\*normalW/g, replace: "mat3(normalMatrix) * " + this.output.associatedVariableName + ".xyz" },
{ search: /normalW/g, replace: worldNormal.associatedVariableName + ".xyz" },
tangentReplaceString
]
});
return this;
};
PerturbNormalBlock.prototype._dumpPropertiesCode = function () {
var codeString = this._codeVariableName + ".invertX = " + this.invertX + ";\r\n";
codeString += this._codeVariableName + ".invertY = " + this.invertY + ";\r\n";
return codeString;
};
PerturbNormalBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.invertX = this.invertX;
serializationObject.invertY = this.invertY;
return serializationObject;
};
PerturbNormalBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.invertX = serializationObject.invertX;
this.invertY = serializationObject.invertY;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("Invert X axis", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Boolean, "PROPERTIES", { "notifiers": { "update": false } })
], PerturbNormalBlock.prototype, "invertX", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("Invert Y axis", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Boolean, "PROPERTIES", { "notifiers": { "update": false } })
], PerturbNormalBlock.prototype, "invertY", void 0);
return PerturbNormalBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.PerturbNormalBlock"] = PerturbNormalBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Fragment/screenSizeBlock.ts":
/*!***********************************************************!*\
!*** ./Materials/Node/Blocks/Fragment/screenSizeBlock.ts ***!
\***********************************************************/
/*! exports provided: ScreenSizeBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScreenSizeBlock", function() { return ScreenSizeBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the screen sizes
*/
var ScreenSizeBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ScreenSizeBlock, _super);
/**
* Creates a new ScreenSizeBlock
* @param name defines the block name
*/
function ScreenSizeBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this.registerOutput("xy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("x", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("y", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ScreenSizeBlock.prototype.getClassName = function () {
return "ScreenSizeBlock";
};
Object.defineProperty(ScreenSizeBlock.prototype, "xy", {
/**
* Gets the xy component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScreenSizeBlock.prototype, "x", {
/**
* Gets the x component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScreenSizeBlock.prototype, "y", {
/**
* Gets the y component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
ScreenSizeBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
var engine = this._scene.getEngine();
effect.setFloat2(this._varName, engine.getRenderWidth(), engine.getRenderWidth());
};
ScreenSizeBlock.prototype.writeOutputs = function (state, varName) {
var code = "";
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
code += this._declareOutput(output, state) + " = " + varName + "." + output.name + ";\r\n";
}
}
return code;
};
ScreenSizeBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
this._scene = state.sharedData.scene;
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
throw "ScreenSizeBlock must only be used in a fragment shader";
}
state.sharedData.bindableBlocks.push(this);
this._varName = state._getFreeVariableName("screenSize");
state._emitUniformFromString(this._varName, "vec2");
state.compilationString += this.writeOutputs(state, this._varName);
return this;
};
return ScreenSizeBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ScreenSizeBlock"] = ScreenSizeBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Input/animatedInputBlockTypes.ts":
/*!****************************************************************!*\
!*** ./Materials/Node/Blocks/Input/animatedInputBlockTypes.ts ***!
\****************************************************************/
/*! exports provided: AnimatedInputBlockTypes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnimatedInputBlockTypes", function() { return AnimatedInputBlockTypes; });
/**
* Enum defining the type of animations supported by InputBlock
*/
var AnimatedInputBlockTypes;
(function (AnimatedInputBlockTypes) {
/** No animation */
AnimatedInputBlockTypes[AnimatedInputBlockTypes["None"] = 0] = "None";
/** Time based animation. Will only work for floats */
AnimatedInputBlockTypes[AnimatedInputBlockTypes["Time"] = 1] = "Time";
})(AnimatedInputBlockTypes || (AnimatedInputBlockTypes = {}));
/***/ }),
/***/ "./Materials/Node/Blocks/Input/index.ts":
/*!**********************************************!*\
!*** ./Materials/Node/Blocks/Input/index.ts ***!
\**********************************************/
/*! exports provided: InputBlock, AnimatedInputBlockTypes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _inputBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputBlock", function() { return _inputBlock__WEBPACK_IMPORTED_MODULE_0__["InputBlock"]; });
/* harmony import */ var _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./animatedInputBlockTypes */ "./Materials/Node/Blocks/Input/animatedInputBlockTypes.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimatedInputBlockTypes", function() { return _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_1__["AnimatedInputBlockTypes"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/Input/inputBlock.ts":
/*!***************************************************!*\
!*** ./Materials/Node/Blocks/Input/inputBlock.ts ***!
\***************************************************/
/*! exports provided: InputBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InputBlock", function() { return InputBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointMode */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Maths/math */ "./Maths/math.ts");
/* harmony import */ var _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./animatedInputBlockTypes */ "./Materials/Node/Blocks/Input/animatedInputBlockTypes.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../../../Materials/materialHelper */ "./Materials/materialHelper.ts");
var remapAttributeName = {
"position2d": "position",
"particle_uv": "vUV",
"particle_color": "vColor",
"particle_texturemask": "textureMask",
"particle_positionw": "vPositionW",
};
var attributeInFragmentOnly = {
"particle_uv": true,
"particle_color": true,
"particle_texturemask": true,
"particle_positionw": true,
};
var attributeAsUniform = {
"particle_texturemask": true,
};
/**
* Block used to expose an input value
*/
var InputBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InputBlock, _super);
/**
* Creates a new InputBlock
* @param name defines the block name
* @param target defines the target of that block (Vertex by default)
* @param type defines the type of the input (can be set to NodeMaterialBlockConnectionPointTypes.AutoDetect)
*/
function InputBlock(name, target, type) {
if (target === void 0) { target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialBlockTargets"].Vertex; }
if (type === void 0) { type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect; }
var _this = _super.call(this, name, target, false, true) || this;
_this._mode = _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined;
_this._animationType = _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_9__["AnimatedInputBlockTypes"].None;
/** Gets or set a value used to limit the range of float values */
_this.min = 0;
/** Gets or set a value used to limit the range of float values */
_this.max = 0;
/** Gets or set a value indicating that this input can only get 0 and 1 values */
_this.isBoolean = false;
/** Gets or sets a value used by the Node Material editor to determine how to configure the current value if it is a matrix */
_this.matrixMode = 0;
/** @hidden */
_this._systemValue = null;
/** Gets or sets a boolean indicating that this input can be edited in the Inspector (false by default) */
_this.visibleInInspector = false;
/** Gets or sets a boolean indicating that the value of this input will not change after a build */
_this.isConstant = false;
/** Gets or sets the group to use to display this block in the Inspector */
_this.groupInInspector = "";
/** Gets an observable raised when the value is changed */
_this.onValueChangedObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_10__["Observable"]();
_this._type = type;
_this.setDefaultValue();
_this.registerOutput("output", type);
return _this;
}
Object.defineProperty(InputBlock.prototype, "type", {
/**
* Gets or sets the connection point type (default is float)
*/
get: function () {
if (this._type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect) {
if (this.isUniform && this.value != null) {
if (!isNaN(this.value)) {
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float;
return this._type;
}
switch (this.value.getClassName()) {
case "Vector2":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2;
return this._type;
case "Vector3":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3;
return this._type;
case "Vector4":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4;
return this._type;
case "Color3":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3;
return this._type;
case "Color4":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4;
return this._type;
case "Matrix":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix;
return this._type;
}
}
if (this.isAttribute) {
switch (this.name) {
case "position":
case "normal":
case "tangent":
case "particle_positionw":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3;
return this._type;
case "uv":
case "uv2":
case "position2d":
case "particle_uv":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2;
return this._type;
case "matricesIndices":
case "matricesWeights":
case "world0":
case "world1":
case "world2":
case "world3":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4;
return this._type;
case "color":
case "particle_color":
case "particle_texturemask":
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4;
return this._type;
}
}
if (this.isSystemValue) {
switch (this._systemValue) {
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].World:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldView:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldViewProjection:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].View:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].ViewProjection:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].Projection:
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix;
return this._type;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].CameraPosition:
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3;
return this._type;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].FogColor:
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3;
return this._type;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].DeltaTime:
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float;
return this._type;
}
}
}
return this._type;
},
enumerable: false,
configurable: true
});
/**
* Validates if a name is a reserve word.
* @param newName the new name to be given to the node.
* @returns false if the name is a reserve word, else true.
*/
InputBlock.prototype.validateBlockName = function (newName) {
if (!this.isAttribute) {
return _super.prototype.validateBlockName.call(this, newName);
}
return true;
};
Object.defineProperty(InputBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
/**
* Set the source of this connection point to a vertex attribute
* @param attributeName defines the attribute name (position, uv, normal, etc...). If not specified it will take the connection point name
* @returns the current connection point
*/
InputBlock.prototype.setAsAttribute = function (attributeName) {
this._mode = _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Attribute;
if (attributeName) {
this.name = attributeName;
}
return this;
};
/**
* Set the source of this connection point to a system value
* @param value define the system value to use (world, view, etc...) or null to switch to manual value
* @returns the current connection point
*/
InputBlock.prototype.setAsSystemValue = function (value) {
this.systemValue = value;
return this;
};
Object.defineProperty(InputBlock.prototype, "value", {
/**
* Gets or sets the value of that point.
* Please note that this value will be ignored if valueCallback is defined
*/
get: function () {
return this._storedValue;
},
set: function (value) {
if (this.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float) {
if (this.isBoolean) {
value = value ? 1 : 0;
}
else if (this.min !== this.max) {
value = Math.max(this.min, value);
value = Math.min(this.max, value);
}
}
this._storedValue = value;
this._mode = _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform;
this.onValueChangedObservable.notifyObservers(this);
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "valueCallback", {
/**
* Gets or sets a callback used to get the value of that point.
* Please note that setting this value will force the connection point to ignore the value property
*/
get: function () {
return this._valueCallback;
},
set: function (value) {
this._valueCallback = value;
this._mode = _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "associatedVariableName", {
/**
* Gets or sets the associated variable name in the shader
*/
get: function () {
return this._associatedVariableName;
},
set: function (value) {
this._associatedVariableName = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "animationType", {
/** Gets or sets the type of animation applied to the input */
get: function () {
return this._animationType;
},
set: function (value) {
this._animationType = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "isUndefined", {
/**
* Gets a boolean indicating that this connection point not defined yet
*/
get: function () {
return this._mode === _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "isUniform", {
/**
* Gets or sets a boolean indicating that this connection point is coming from an uniform.
* In this case the connection point name must be the name of the uniform to use.
* Can only be set on inputs
*/
get: function () {
return this._mode === _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform;
},
set: function (value) {
this._mode = value ? _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform : _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined;
this.associatedVariableName = "";
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "isAttribute", {
/**
* Gets or sets a boolean indicating that this connection point is coming from an attribute.
* In this case the connection point name must be the name of the attribute to use
* Can only be set on inputs
*/
get: function () {
return this._mode === _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Attribute;
},
set: function (value) {
this._mode = value ? _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Attribute : _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined;
this.associatedVariableName = "";
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "isVarying", {
/**
* Gets or sets a boolean indicating that this connection point is generating a varying variable.
* Can only be set on exit points
*/
get: function () {
return this._mode === _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Varying;
},
set: function (value) {
this._mode = value ? _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Varying : _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Undefined;
this.associatedVariableName = "";
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "isSystemValue", {
/**
* Gets a boolean indicating that the current connection point is a system value
*/
get: function () {
return this._systemValue != null;
},
enumerable: false,
configurable: true
});
Object.defineProperty(InputBlock.prototype, "systemValue", {
/**
* Gets or sets the current well known value or null if not defined as a system value
*/
get: function () {
return this._systemValue;
},
set: function (value) {
this._mode = _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform;
this.associatedVariableName = "";
this._systemValue = value;
},
enumerable: false,
configurable: true
});
/**
* Gets the current class name
* @returns the class name
*/
InputBlock.prototype.getClassName = function () {
return "InputBlock";
};
/**
* Animate the input if animationType !== None
* @param scene defines the rendering scene
*/
InputBlock.prototype.animate = function (scene) {
switch (this._animationType) {
case _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_9__["AnimatedInputBlockTypes"].Time: {
if (this.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float) {
this.value += scene.getAnimationRatio() * 0.01;
}
break;
}
}
};
InputBlock.prototype._emitDefine = function (define) {
if (define[0] === "!") {
return "#ifndef " + define.substring(1) + "\r\n";
}
return "#ifdef " + define + "\r\n";
};
InputBlock.prototype.initialize = function (state) {
this.associatedVariableName = "";
};
/**
* Set the input block to its default value (based on its type)
*/
InputBlock.prototype.setDefaultValue = function () {
switch (this.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float:
this.value = 0;
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2:
this.value = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector2"].Zero();
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3:
this.value = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector3"].Zero();
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4:
this.value = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector4"].Zero();
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3:
this.value = _Maths_math__WEBPACK_IMPORTED_MODULE_8__["Color3"].White();
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4:
this.value = new _Maths_math__WEBPACK_IMPORTED_MODULE_8__["Color4"](1, 1, 1, 1);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix:
this.value = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Matrix"].Identity();
break;
}
};
InputBlock.prototype._emitConstant = function (state) {
switch (this.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float:
return "" + state._emitFloat(this.value);
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2:
return "vec2(" + this.value.x + ", " + this.value.y + ")";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3:
return "vec3(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ")";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4:
return "vec4(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ", " + this.value.w + ")";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3:
return "vec3(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ")";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4:
return "vec4(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ", " + this.value.a + ")";
}
return "";
};
Object.defineProperty(InputBlock.prototype, "_noContextSwitch", {
/** @hidden */
get: function () {
return attributeInFragmentOnly[this.name];
},
enumerable: false,
configurable: true
});
InputBlock.prototype._emit = function (state, define) {
var _a;
// Uniforms
if (this.isUniform) {
if (!this.associatedVariableName) {
this.associatedVariableName = state._getFreeVariableName("u_" + this.name);
}
if (this.isConstant) {
if (state.constants.indexOf(this.associatedVariableName) !== -1) {
return;
}
state.constants.push(this.associatedVariableName);
state._constantDeclaration += this._declareOutput(this.output, state) + (" = " + this._emitConstant(state) + ";\r\n");
return;
}
if (state.uniforms.indexOf(this.associatedVariableName) !== -1) {
return;
}
state.uniforms.push(this.associatedVariableName);
if (define) {
state._uniformDeclaration += this._emitDefine(define);
}
state._uniformDeclaration += "uniform " + state._getGLType(this.type) + " " + this.associatedVariableName + ";\r\n";
if (define) {
state._uniformDeclaration += "#endif\r\n";
}
// well known
var hints = state.sharedData.hints;
if (this._systemValue !== null && this._systemValue !== undefined) {
switch (this._systemValue) {
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldView:
hints.needWorldViewMatrix = true;
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldViewProjection:
hints.needWorldViewProjectionMatrix = true;
break;
}
}
else {
if (this._animationType !== _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_9__["AnimatedInputBlockTypes"].None) {
state.sharedData.animatedInputs.push(this);
}
}
return;
}
// Attribute
if (this.isAttribute) {
this.associatedVariableName = (_a = remapAttributeName[this.name]) !== null && _a !== void 0 ? _a : this.name;
if (this.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialBlockTargets"].Vertex && state._vertexState) { // Attribute for fragment need to be carried over by varyings
if (attributeInFragmentOnly[this.name]) {
if (attributeAsUniform[this.name]) {
state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define);
}
else {
state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define);
}
}
else {
this._emit(state._vertexState, define);
}
return;
}
if (state.attributes.indexOf(this.associatedVariableName) !== -1) {
return;
}
state.attributes.push(this.associatedVariableName);
if (attributeInFragmentOnly[this.name]) {
if (attributeAsUniform[this.name]) {
state._emitUniformFromString(this.associatedVariableName, state._getGLType(this.type), define);
}
else {
state._emitVaryingFromString(this.associatedVariableName, state._getGLType(this.type), define);
}
}
else {
if (define) {
state._attributeDeclaration += this._emitDefine(define);
}
state._attributeDeclaration += "attribute " + state._getGLType(this.type) + " " + this.associatedVariableName + ";\r\n";
if (define) {
state._attributeDeclaration += "#endif\r\n";
}
}
}
};
/** @hidden */
InputBlock.prototype._transmitWorld = function (effect, world, worldView, worldViewProjection) {
if (!this._systemValue) {
return;
}
var variableName = this.associatedVariableName;
switch (this._systemValue) {
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].World:
effect.setMatrix(variableName, world);
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldView:
effect.setMatrix(variableName, worldView);
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldViewProjection:
effect.setMatrix(variableName, worldViewProjection);
break;
}
};
/** @hidden */
InputBlock.prototype._transmit = function (effect, scene) {
if (this.isAttribute) {
return;
}
var variableName = this.associatedVariableName;
if (this._systemValue) {
switch (this._systemValue) {
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].World:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldView:
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].WorldViewProjection:
return;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].View:
effect.setMatrix(variableName, scene.getViewMatrix());
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].Projection:
effect.setMatrix(variableName, scene.getProjectionMatrix());
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].ViewProjection:
effect.setMatrix(variableName, scene.getTransformMatrix());
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].CameraPosition:
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_11__["MaterialHelper"].BindEyePosition(effect, scene, variableName);
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].FogColor:
effect.setColor3(variableName, scene.fogColor);
break;
case _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].DeltaTime:
effect.setFloat(variableName, scene.deltaTime / 1000.0);
}
return;
}
var value = this._valueCallback ? this._valueCallback() : this._storedValue;
if (value === null) {
return;
}
switch (this.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float:
effect.setFloat(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Int:
effect.setInt(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3:
effect.setColor3(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4:
effect.setDirectColor4(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2:
effect.setVector2(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3:
effect.setVector3(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4:
effect.setVector4(variableName, value);
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix:
effect.setMatrix(variableName, value);
break;
}
};
InputBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (this.isUniform || this.isSystemValue) {
state.sharedData.inputBlocks.push(this);
}
this._emit(state);
};
InputBlock.prototype._dumpPropertiesCode = function () {
var variableName = this._codeVariableName;
if (this.isAttribute) {
return variableName + ".setAsAttribute(\"" + this.name + "\");\r\n";
}
if (this.isSystemValue) {
return variableName + ".setAsSystemValue(BABYLON.NodeMaterialSystemValues." + _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"][this._systemValue] + ");\r\n";
}
if (this.isUniform) {
var codes = [];
var valueString = "";
switch (this.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float:
valueString = "" + this.value;
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2:
valueString = "new BABYLON.Vector2(" + this.value.x + ", " + this.value.y + ")";
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3:
valueString = "new BABYLON.Vector3(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ")";
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4:
valueString = "new BABYLON.Vector4(" + this.value.x + ", " + this.value.y + ", " + this.value.z + ", " + this.value.w + ")";
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3:
valueString = "new BABYLON.Color3(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ")";
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4:
valueString = "new BABYLON.Color4(" + this.value.r + ", " + this.value.g + ", " + this.value.b + ", " + this.value.a + ")";
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix:
valueString = "BABYLON.Matrix.FromArray([" + this.value.m + "])";
break;
}
// Common Property "Value"
codes.push(variableName + ".value = " + valueString);
// Float-Value-Specific Properties
if (this.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float) {
codes.push(variableName + ".min = " + this.min, variableName + ".max = " + this.max, variableName + ".isBoolean = " + this.isBoolean, variableName + ".matrixMode = " + this.matrixMode, variableName + ".animationType = BABYLON.AnimatedInputBlockTypes." + _animatedInputBlockTypes__WEBPACK_IMPORTED_MODULE_9__["AnimatedInputBlockTypes"][this.animationType]);
}
// Common Property "Type"
codes.push(variableName + ".isConstant = " + this.isConstant, variableName + ".visibleInInspector = " + this.visibleInInspector);
codes.push('');
return codes.join(';\r\n');
}
return "";
};
InputBlock.prototype.dispose = function () {
this.onValueChangedObservable.clear();
_super.prototype.dispose.call(this);
};
InputBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.type = this.type;
serializationObject.mode = this._mode;
serializationObject.systemValue = this._systemValue;
serializationObject.animationType = this._animationType;
serializationObject.visibleInInspector = this.visibleInInspector;
serializationObject.min = this.min;
serializationObject.max = this.max;
serializationObject.isBoolean = this.isBoolean;
serializationObject.matrixMode = this.matrixMode;
serializationObject.isConstant = this.isConstant;
serializationObject.groupInInspector = this.groupInInspector;
if (this._storedValue != null && this._mode === _Enums_nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointMode"].Uniform) {
if (this._storedValue.asArray) {
serializationObject.valueType = "BABYLON." + this._storedValue.getClassName();
serializationObject.value = this._storedValue.asArray();
}
else {
serializationObject.valueType = "number";
serializationObject.value = this._storedValue;
}
}
return serializationObject;
};
InputBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
this._mode = serializationObject.mode;
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this._type = serializationObject.type;
this._systemValue = serializationObject.systemValue || serializationObject.wellKnownValue;
this._animationType = serializationObject.animationType;
this.visibleInInspector = serializationObject.visibleInInspector;
this.min = serializationObject.min || 0;
this.max = serializationObject.max || 0;
this.isBoolean = !!serializationObject.isBoolean;
this.matrixMode = serializationObject.matrixMode || 0;
this.isConstant = !!serializationObject.isConstant;
this.groupInInspector = serializationObject.groupInInspector || "";
if (!serializationObject.valueType) {
return;
}
if (serializationObject.valueType === "number") {
this._storedValue = serializationObject.value;
}
else {
var valueType = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].GetClass(serializationObject.valueType);
if (valueType) {
this._storedValue = valueType.FromArray(serializationObject.value);
}
}
};
return InputBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.InputBlock"] = InputBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/ambientOcclusionBlock.ts":
/*!************************************************************!*\
!*** ./Materials/Node/Blocks/PBR/ambientOcclusionBlock.ts ***!
\************************************************************/
/*! exports provided: AmbientOcclusionBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AmbientOcclusionBlock", function() { return AmbientOcclusionBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/**
* Block used to implement the ambient occlusion module of the PBR material
*/
var AmbientOcclusionBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AmbientOcclusionBlock, _super);
/**
* Create a new AmbientOcclusionBlock
* @param name defines the block name
*/
function AmbientOcclusionBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) || this;
/**
* Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
*/
_this.useAmbientInGrayScale = false;
_this._isUnique = true;
_this.registerInput("texture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("intensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("directLightIntensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("ambientOcclusion", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_7__["NodeMaterialConnectionPointCustomObject"]("ambientOcclusion", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Output, AmbientOcclusionBlock, "AOBlock"));
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
AmbientOcclusionBlock.prototype.initialize = function (state) {
state._excludeVariableName("aoOut");
};
/**
* Gets the current class name
* @returns the class name
*/
AmbientOcclusionBlock.prototype.getClassName = function () {
return "AmbientOcclusionBlock";
};
Object.defineProperty(AmbientOcclusionBlock.prototype, "texture", {
/**
* Gets the texture input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AmbientOcclusionBlock.prototype, "intensity", {
/**
* Gets the texture intensity component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AmbientOcclusionBlock.prototype, "directLightIntensity", {
/**
* Gets the direct light intensity input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AmbientOcclusionBlock.prototype, "ambientOcclusion", {
/**
* Gets the ambient occlusion object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
/**
* Gets the main code of the block (fragment side)
* @param block instance of an AmbientOcclusionBlock or null if the code must be generated without an active ambient occlusion module
* @returns the shader code
*/
AmbientOcclusionBlock.GetCode = function (block) {
var code = "ambientOcclusionOutParams aoOut;\r\n";
var aoTexture = (block === null || block === void 0 ? void 0 : block.texture.isConnected) ? block.texture.associatedVariableName : "vec3(0.)";
var aoIntensity = (block === null || block === void 0 ? void 0 : block.intensity.isConnected) ? block.intensity.associatedVariableName : "1.";
code += "ambientOcclusionBlock(\n #ifdef AMBIENT\n " + aoTexture + ",\n vec4(0., 1.0, " + aoIntensity + ", 0.),\n #endif\n aoOut\n );\r\n";
return code;
};
AmbientOcclusionBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
defines.setValue("AMBIENT", this.texture.isConnected, true);
defines.setValue("AMBIENTINGRAYSCALE", this.useAmbientInGrayScale, true);
};
AmbientOcclusionBlock.prototype._buildBlock = function (state) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.blocksWithDefines.push(this);
}
return this;
};
AmbientOcclusionBlock.prototype._dumpPropertiesCode = function () {
var codeString;
codeString = this._codeVariableName + ".useAmbientInGrayScale = " + this.useAmbientInGrayScale + ";\r\n";
return codeString;
};
AmbientOcclusionBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.useAmbientInGrayScale = this.useAmbientInGrayScale;
return serializationObject;
};
AmbientOcclusionBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.useAmbientInGrayScale = serializationObject.useAmbientInGrayScale;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["editableInPropertyPage"])("Ambient in gray scale", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["PropertyTypeForEdition"].Boolean, "AMBIENT", { "notifiers": { "update": true } })
], AmbientOcclusionBlock.prototype, "useAmbientInGrayScale", void 0);
return AmbientOcclusionBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__["_TypeStore"].RegisteredTypes["BABYLON.AmbientOcclusionBlock"] = AmbientOcclusionBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/anisotropyBlock.ts":
/*!******************************************************!*\
!*** ./Materials/Node/Blocks/PBR/anisotropyBlock.ts ***!
\******************************************************/
/*! exports provided: AnisotropyBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AnisotropyBlock", function() { return AnisotropyBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/**
* Block used to implement the anisotropy module of the PBR material
*/
var AnisotropyBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AnisotropyBlock, _super);
/**
* Create a new AnisotropyBlock
* @param name defines the block name
*/
function AnisotropyBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) || this;
_this._isUnique = true;
_this.registerInput("intensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("direction", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("texture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, true); // need this property and the next one in case there's no PerturbNormal block connected to the main PBR block
_this.registerInput("worldTangent", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true);
_this.registerOutput("anisotropy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialConnectionPointCustomObject"]("anisotropy", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Output, AnisotropyBlock, "AnisotropyBlock"));
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
AnisotropyBlock.prototype.initialize = function (state) {
state._excludeVariableName("anisotropicOut");
state._excludeVariableName("TBN");
};
/**
* Gets the current class name
* @returns the class name
*/
AnisotropyBlock.prototype.getClassName = function () {
return "AnisotropyBlock";
};
Object.defineProperty(AnisotropyBlock.prototype, "intensity", {
/**
* Gets the intensity input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AnisotropyBlock.prototype, "direction", {
/**
* Gets the direction input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AnisotropyBlock.prototype, "texture", {
/**
* Gets the texture input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AnisotropyBlock.prototype, "uv", {
/**
* Gets the uv input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AnisotropyBlock.prototype, "worldTangent", {
/**
* Gets the worldTangent input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AnisotropyBlock.prototype, "anisotropy", {
/**
* Gets the anisotropy object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
AnisotropyBlock.prototype._generateTBNSpace = function (state) {
var code = "";
var comments = "//" + this.name;
var uv = this.uv;
var worldPosition = this.worldPositionConnectionPoint;
var worldNormal = this.worldNormalConnectionPoint;
var worldTangent = this.worldTangent;
if (!uv.isConnected) {
// we must set the uv input as optional because we may not end up in this method (in case a PerturbNormal block is linked to the PBR material)
// in which case uv is not required. But if we do come here, we do need the uv, so we have to raise an error but not with throw, else
// it will stop the building of the node material and will lead to errors in the editor!
console.error("You must connect the 'uv' input of the Anisotropy block!");
}
state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
var tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" };
if (worldTangent.isConnected) {
code += "vec3 tbnNormal = normalize(" + worldNormal.associatedVariableName + ".xyz);\r\n";
code += "vec3 tbnTangent = normalize(" + worldTangent.associatedVariableName + ".xyz);\r\n";
code += "vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r\n";
code += "mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n";
}
code += "\n #if defined(" + (worldTangent.isConnected ? "TANGENT" : "IGNORE") + ") && defined(NORMAL)\n mat3 TBN = vTBN;\n #else\n mat3 TBN = cotangent_frame(" + (worldNormal.associatedVariableName + ".xyz") + ", " + ("v_" + worldPosition.associatedVariableName + ".xyz") + ", " + (uv.isConnected ? uv.associatedVariableName : "vec2(0.)") + ", vec2(1., 1.));\n #endif\r\n";
state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, {
replaceStrings: [
tangentReplaceString,
]
});
return code;
};
/**
* Gets the main code of the block (fragment side)
* @param state current state of the node material building
* @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated
* @returns the shader code
*/
AnisotropyBlock.prototype.getCode = function (state, generateTBNSpace) {
if (generateTBNSpace === void 0) { generateTBNSpace = false; }
var code = "";
if (generateTBNSpace) {
code += this._generateTBNSpace(state);
}
var intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.0";
var direction = this.direction.isConnected ? this.direction.associatedVariableName : "vec2(1., 0.)";
var texture = this.texture.isConnected ? this.texture.associatedVariableName : "vec3(0.)";
code += "anisotropicOutParams anisotropicOut;\n anisotropicBlock(\n vec3(" + direction + ", " + intensity + "),\n #ifdef ANISOTROPIC_TEXTURE\n " + texture + ",\n #endif\n TBN,\n normalW,\n viewDirectionW,\n anisotropicOut\n );\r\n";
return code;
};
AnisotropyBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
defines.setValue("ANISOTROPIC", true);
defines.setValue("ANISOTROPIC_TEXTURE", this.texture.isConnected, true);
};
AnisotropyBlock.prototype._buildBlock = function (state) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.blocksWithDefines.push(this);
}
return this;
};
return AnisotropyBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.AnisotropyBlock"] = AnisotropyBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/clearCoatBlock.ts":
/*!*****************************************************!*\
!*** ./Materials/Node/Blocks/PBR/clearCoatBlock.ts ***!
\*****************************************************/
/*! exports provided: ClearCoatBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClearCoatBlock", function() { return ClearCoatBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/**
* Block used to implement the clear coat module of the PBR material
*/
var ClearCoatBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ClearCoatBlock, _super);
/**
* Create a new ClearCoatBlock
* @param name defines the block name
*/
function ClearCoatBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) || this;
_this._isUnique = true;
_this.registerInput("intensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("roughness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("ior", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("texture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("bumpTexture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("tintColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("tintAtDistance", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("tintThickness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("worldTangent", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true);
_this.registerOutput("clearcoat", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_7__["NodeMaterialConnectionPointCustomObject"]("clearcoat", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Output, ClearCoatBlock, "ClearCoatBlock"));
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
ClearCoatBlock.prototype.initialize = function (state) {
state._excludeVariableName("clearcoatOut");
state._excludeVariableName("vClearCoatParams");
state._excludeVariableName("vClearCoatTintParams");
state._excludeVariableName("vClearCoatRefractionParams");
state._excludeVariableName("vClearCoatTangentSpaceParams");
};
/**
* Gets the current class name
* @returns the class name
*/
ClearCoatBlock.prototype.getClassName = function () {
return "ClearCoatBlock";
};
Object.defineProperty(ClearCoatBlock.prototype, "intensity", {
/**
* Gets the intensity input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "roughness", {
/**
* Gets the roughness input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "ior", {
/**
* Gets the ior input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "texture", {
/**
* Gets the texture input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "bumpTexture", {
/**
* Gets the bump texture input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "uv", {
/**
* Gets the uv input component
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "tintColor", {
/**
* Gets the tint color input component
*/
get: function () {
return this._inputs[6];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "tintAtDistance", {
/**
* Gets the tint "at distance" input component
*/
get: function () {
return this._inputs[7];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "tintThickness", {
/**
* Gets the tint thickness input component
*/
get: function () {
return this._inputs[8];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "worldTangent", {
/**
* Gets the world tangent input component
*/
get: function () {
return this._inputs[9];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClearCoatBlock.prototype, "clearcoat", {
/**
* Gets the clear coat object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ClearCoatBlock.prototype.autoConfigure = function (material) {
if (!this.intensity.isConnected) {
var intensityInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("ClearCoat intensity", _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
intensityInput.value = 1;
intensityInput.output.connectTo(this.intensity);
}
};
ClearCoatBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
defines.setValue("CLEARCOAT", true);
defines.setValue("CLEARCOAT_TEXTURE", this.texture.isConnected, true);
defines.setValue("CLEARCOAT_TINT", this.tintColor.isConnected || this.tintThickness.isConnected || this.tintAtDistance.isConnected, true);
defines.setValue("CLEARCOAT_BUMP", this.bumpTexture.isConnected, true);
defines.setValue("CLEARCOAT_DEFAULTIOR", this.ior.isConnected ? this.ior.connectInputBlock.value === 1.5 : false, true);
};
ClearCoatBlock.prototype.bind = function (effect, nodeMaterial, mesh, subMesh) {
var _a, _b;
_super.prototype.bind.call(this, effect, nodeMaterial, mesh);
// Clear Coat Refraction params
var indexOfRefraction = (_b = (_a = this.ior.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 1.5;
var a = 1 - indexOfRefraction;
var b = 1 + indexOfRefraction;
var f0 = Math.pow((-a / b), 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.
var eta = 1 / indexOfRefraction;
effect.setFloat4("vClearCoatRefractionParams", f0, eta, a, b);
// Clear Coat tangent space params
var mainPBRBlock = this.clearcoat.hasEndpoints ? this.clearcoat.endpoints[0].ownerBlock : null;
var perturbedNormalBlock = (mainPBRBlock === null || mainPBRBlock === void 0 ? void 0 : mainPBRBlock.perturbedNormal.isConnected) ? mainPBRBlock.perturbedNormal.connectedPoint.ownerBlock : null;
if (this._scene._mirroredCameraPosition) {
effect.setFloat2("vClearCoatTangentSpaceParams", (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertX) ? 1.0 : -1.0, (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertY) ? 1.0 : -1.0);
}
else {
effect.setFloat2("vClearCoatTangentSpaceParams", (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertX) ? -1.0 : 1.0, (perturbedNormalBlock === null || perturbedNormalBlock === void 0 ? void 0 : perturbedNormalBlock.invertY) ? -1.0 : 1.0);
}
};
ClearCoatBlock.prototype._generateTBNSpace = function (state, worldPositionVarName, worldNormalVarName) {
var code = "";
var comments = "//" + this.name;
var worldTangent = this.worldTangent;
state._emitExtension("derivatives", "#extension GL_OES_standard_derivatives : enable");
var tangentReplaceString = { search: /defined\(TANGENT\)/g, replace: worldTangent.isConnected ? "defined(TANGENT)" : "defined(IGNORE)" };
if (worldTangent.isConnected) {
code += "vec3 tbnNormal = normalize(" + worldNormalVarName + ".xyz);\r\n";
code += "vec3 tbnTangent = normalize(" + worldTangent.associatedVariableName + ".xyz);\r\n";
code += "vec3 tbnBitangent = cross(tbnNormal, tbnTangent);\r\n";
code += "mat3 vTBN = mat3(tbnTangent, tbnBitangent, tbnNormal);\r\n";
}
state._emitFunctionFromInclude("bumpFragmentMainFunctions", comments, {
replaceStrings: [
tangentReplaceString,
]
});
return code;
};
/**
* Gets the main code of the block (fragment side)
* @param state current state of the node material building
* @param ccBlock instance of a ClearCoatBlock or null if the code must be generated without an active clear coat module
* @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module
* @param worldPosVarName name of the variable holding the world position
* @param generateTBNSpace if true, the code needed to create the TBN coordinate space is generated
* @param vTBNAvailable indicate that the vTBN variable is already existing because it has already been generated by another block (PerturbNormal or Anisotropy)
* @param worldNormalVarName name of the variable holding the world normal
* @returns the shader code
*/
ClearCoatBlock.GetCode = function (state, ccBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, worldNormalVarName) {
var code = "";
var intensity = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.intensity.isConnected) ? ccBlock.intensity.associatedVariableName : "1.";
var roughness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.roughness.isConnected) ? ccBlock.roughness.associatedVariableName : "0.";
var texture = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.texture.isConnected) ? ccBlock.texture.associatedVariableName : "vec2(0.)";
var bumpTexture = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.bumpTexture.isConnected) ? ccBlock.bumpTexture.associatedVariableName : "vec4(0.)";
var uv = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.uv.isConnected) ? ccBlock.uv.associatedVariableName : "vec2(0.)";
var tintColor = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintColor.isConnected) ? ccBlock.tintColor.associatedVariableName : "vec3(1.)";
var tintThickness = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintThickness.isConnected) ? ccBlock.tintThickness.associatedVariableName : "1.";
var tintAtDistance = (ccBlock === null || ccBlock === void 0 ? void 0 : ccBlock.tintAtDistance.isConnected) ? ccBlock.tintAtDistance.associatedVariableName : "1.";
var tintTexture = "vec4(0.)";
if (ccBlock) {
state._emitUniformFromString("vClearCoatRefractionParams", "vec4");
state._emitUniformFromString("vClearCoatTangentSpaceParams", "vec2");
}
if (generateTBNSpace && ccBlock) {
code += ccBlock._generateTBNSpace(state, worldPosVarName, worldNormalVarName);
vTBNAvailable = ccBlock.worldTangent.isConnected;
}
code += "clearcoatOutParams clearcoatOut;\n\n #ifdef CLEARCOAT\n vec2 vClearCoatParams = vec2(" + intensity + ", " + roughness + ");\n vec4 vClearCoatTintParams = vec4(" + tintColor + ", " + tintThickness + ");\n\n clearcoatBlock(\n " + worldPosVarName + ".xyz,\n geometricNormalW,\n viewDirectionW,\n vClearCoatParams,\n specularEnvironmentR0,\n #ifdef CLEARCOAT_TEXTURE\n " + texture + ".rg,\n #endif\n #ifdef CLEARCOAT_TINT\n vClearCoatTintParams,\n " + tintAtDistance + ",\n vClearCoatRefractionParams,\n #ifdef CLEARCOAT_TINT_TEXTURE\n " + tintTexture + ",\n #endif\n #endif\n #ifdef CLEARCOAT_BUMP\n vec2(0., 1.),\n " + bumpTexture + ",\n " + uv + ",\n #if defined(" + (vTBNAvailable ? "TANGENT" : "IGNORE") + ") && defined(NORMAL)\n vTBN,\n #else\n vClearCoatTangentSpaceParams,\n #endif\n #ifdef OBJECTSPACE_NORMALMAP\n normalMatrix,\n #endif\n #endif\n #if defined(FORCENORMALFORWARD) && defined(NORMAL)\n faceNormal,\n #endif\n #ifdef REFLECTION\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor) + ",\n vLightingIntensity,\n #ifdef " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) + "\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName) + ",\n #else\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName) + ",\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) + "\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName) + ",\n #else\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName) + ",\n #endif\n #endif\n #endif\n #if defined(ENVIRONMENTBRDF) && !defined(" + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) + ")\n #ifdef RADIANCEOCCLUSION\n ambientMonochrome,\n #endif\n #endif\n clearcoatOut\n );\n #else\n clearcoatOut.specularEnvironmentR0 = specularEnvironmentR0;\n #endif\r\n";
return code;
};
ClearCoatBlock.prototype._buildBlock = function (state) {
this._scene = state.sharedData.scene;
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.bindableBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
}
return this;
};
return ClearCoatBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.ClearCoatBlock"] = ClearCoatBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/index.ts":
/*!********************************************!*\
!*** ./Materials/Node/Blocks/PBR/index.ts ***!
\********************************************/
/*! exports provided: PBRMetallicRoughnessBlock, SheenBlock, AmbientOcclusionBlock, ReflectivityBlock, AnisotropyBlock, ReflectionBlock, ClearCoatBlock, RefractionBlock, SubSurfaceBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _pbrMetallicRoughnessBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pbrMetallicRoughnessBlock */ "./Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessBlock", function() { return _pbrMetallicRoughnessBlock__WEBPACK_IMPORTED_MODULE_0__["PBRMetallicRoughnessBlock"]; });
/* harmony import */ var _sheenBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./sheenBlock */ "./Materials/Node/Blocks/PBR/sheenBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SheenBlock", function() { return _sheenBlock__WEBPACK_IMPORTED_MODULE_1__["SheenBlock"]; });
/* harmony import */ var _ambientOcclusionBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ambientOcclusionBlock */ "./Materials/Node/Blocks/PBR/ambientOcclusionBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmbientOcclusionBlock", function() { return _ambientOcclusionBlock__WEBPACK_IMPORTED_MODULE_2__["AmbientOcclusionBlock"]; });
/* harmony import */ var _reflectivityBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./reflectivityBlock */ "./Materials/Node/Blocks/PBR/reflectivityBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectivityBlock", function() { return _reflectivityBlock__WEBPACK_IMPORTED_MODULE_3__["ReflectivityBlock"]; });
/* harmony import */ var _anisotropyBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./anisotropyBlock */ "./Materials/Node/Blocks/PBR/anisotropyBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnisotropyBlock", function() { return _anisotropyBlock__WEBPACK_IMPORTED_MODULE_4__["AnisotropyBlock"]; });
/* harmony import */ var _reflectionBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./reflectionBlock */ "./Materials/Node/Blocks/PBR/reflectionBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionBlock", function() { return _reflectionBlock__WEBPACK_IMPORTED_MODULE_5__["ReflectionBlock"]; });
/* harmony import */ var _clearCoatBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./clearCoatBlock */ "./Materials/Node/Blocks/PBR/clearCoatBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClearCoatBlock", function() { return _clearCoatBlock__WEBPACK_IMPORTED_MODULE_6__["ClearCoatBlock"]; });
/* harmony import */ var _refractionBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./refractionBlock */ "./Materials/Node/Blocks/PBR/refractionBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionBlock", function() { return _refractionBlock__WEBPACK_IMPORTED_MODULE_7__["RefractionBlock"]; });
/* harmony import */ var _subSurfaceBlock__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./subSurfaceBlock */ "./Materials/Node/Blocks/PBR/subSurfaceBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubSurfaceBlock", function() { return _subSurfaceBlock__WEBPACK_IMPORTED_MODULE_8__["SubSurfaceBlock"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.ts":
/*!****************************************************************!*\
!*** ./Materials/Node/Blocks/PBR/pbrMetallicRoughnessBlock.ts ***!
\****************************************************************/
/*! exports provided: PBRMetallicRoughnessBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessBlock", function() { return PBRMetallicRoughnessBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../PBR/pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/* harmony import */ var _ambientOcclusionBlock__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./ambientOcclusionBlock */ "./Materials/Node/Blocks/PBR/ambientOcclusionBlock.ts");
/* harmony import */ var _sheenBlock__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./sheenBlock */ "./Materials/Node/Blocks/PBR/sheenBlock.ts");
/* harmony import */ var _reflectivityBlock__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./reflectivityBlock */ "./Materials/Node/Blocks/PBR/reflectivityBlock.ts");
/* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts");
/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../../materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _anisotropyBlock__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./anisotropyBlock */ "./Materials/Node/Blocks/PBR/anisotropyBlock.ts");
/* harmony import */ var _reflectionBlock__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./reflectionBlock */ "./Materials/Node/Blocks/PBR/reflectionBlock.ts");
/* harmony import */ var _clearCoatBlock__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./clearCoatBlock */ "./Materials/Node/Blocks/PBR/clearCoatBlock.ts");
/* harmony import */ var _subSurfaceBlock__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./subSurfaceBlock */ "./Materials/Node/Blocks/PBR/subSurfaceBlock.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../../../../Engines/constants */ "./Engines/constants.ts");
var mapOutputToVariable = {
"ambient": ["finalAmbient", ""],
"diffuse": ["finalDiffuse", ""],
"specular": ["finalSpecularScaled", "!defined(UNLIT) && defined(SPECULARTERM)"],
"sheenDir": ["finalSheenScaled", "!defined(UNLIT) && defined(SHEEN)"],
"clearcoatDir": ["finalClearCoatScaled", "!defined(UNLIT) && defined(CLEARCOAT)"],
"diffuseInd": ["finalIrradiance", "!defined(UNLIT) && defined(REFLECTION)"],
"specularInd": ["finalRadianceScaled", "!defined(UNLIT) && defined(REFLECTION)"],
"sheenInd": ["sheenOut.finalSheenRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(SHEEN) && defined(ENVIRONMENTBRDF)"],
"clearcoatInd": ["clearcoatOut.finalClearCoatRadianceScaled", "!defined(UNLIT) && defined(REFLECTION) && defined(CLEARCOAT)"],
"refraction": ["subSurfaceOut.finalRefraction", "!defined(UNLIT) && defined(SS_REFRACTION)"],
"lighting": ["finalColor.rgb", ""],
"shadow": ["shadow", ""],
"alpha": ["alpha", ""],
};
/**
* Block used to implement the PBR metallic/roughness model
*/
var PBRMetallicRoughnessBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRMetallicRoughnessBlock, _super);
/**
* Create a new ReflectionBlock
* @param name defines the block name
*/
function PBRMetallicRoughnessBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].VertexAndFragment) || this;
_this._environmentBRDFTexture = null;
/**
* Intensity of the direct lights e.g. the four lights available in your scene.
* This impacts both the direct diffuse and specular highlights.
*/
_this.directIntensity = 1.0;
/**
* Intensity of the environment e.g. how much the environment will light the object
* either through harmonics for rough material or through the refelction for shiny ones.
*/
_this.environmentIntensity = 1.0;
/**
* This is a special control allowing the reduction of the specular highlights coming from the
* four lights of the scene. Those highlights may not be needed in full environment lighting.
*/
_this.specularIntensity = 1.0;
/**
* Defines the falloff type used in this material.
* It by default is Physical.
*/
_this.lightFalloff = 0;
/**
* Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
*/
_this.useAlphaFromAlbedoTexture = false;
/**
* Specifies that alpha test should be used
*/
_this.useAlphaTest = false;
/**
* Defines the alpha limits in alpha test mode.
*/
_this.alphaTestCutoff = 0.5;
/**
* Specifies that alpha blending should be used
*/
_this.useAlphaBlending = false;
/**
* Defines if the alpha value should be determined via the rgb values.
* If true the luminance of the pixel might be used to find the corresponding alpha value.
*/
_this.opacityRGB = false;
/**
* Specifies that the material will keeps the reflection highlights over a transparent surface (only the most luminous ones).
* A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
*/
_this.useRadianceOverAlpha = true;
/**
* Specifies that the material will keeps the specular highlights over a transparent surface (only the most luminous ones).
* A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
*/
_this.useSpecularOverAlpha = true;
/**
* Enables specular anti aliasing in the PBR shader.
* It will both interacts on the Geometry for analytical and IBL lighting.
* It also prefilter the roughness map based on the bump values.
*/
_this.enableSpecularAntiAliasing = false;
/**
* Enables realtime filtering on the texture.
*/
_this.realTimeFiltering = false;
/**
* Quality switch for realtime filtering
*/
_this.realTimeFilteringQuality = _Engines_constants__WEBPACK_IMPORTED_MODULE_21__["Constants"].TEXTURE_FILTERING_QUALITY_LOW;
/**
* Defines if the material uses energy conservation.
*/
_this.useEnergyConservation = true;
/**
* This parameters will enable/disable radiance occlusion by preventing the radiance to lit
* too much the area relying on ambient texture to define their ambient occlusion.
*/
_this.useRadianceOcclusion = true;
/**
* This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
* makes the reflect vector face the model (under horizon).
*/
_this.useHorizonOcclusion = true;
/**
* If set to true, no lighting calculations will be applied.
*/
_this.unlit = false;
/**
* Force normal to face away from face.
*/
_this.forceNormalForward = false;
/**
* Defines the material debug mode.
* It helps seeing only some components of the material while troubleshooting.
*/
_this.debugMode = 0;
/**
* Specify from where on screen the debug mode should start.
* The value goes from -1 (full screen) to 1 (not visible)
* It helps with side by side comparison against the final render
* This defaults to 0
*/
_this.debugLimit = 0;
/**
* As the default viewing range might not be enough (if the ambient is really small for instance)
* You can use the factor to better multiply the final value.
*/
_this.debugFactor = 1;
_this._isUnique = true;
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("worldNormal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("perturbedNormal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("cameraPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("baseColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("opacityTexture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("ambientColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("reflectivity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("reflectivity", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _reflectivityBlock__WEBPACK_IMPORTED_MODULE_14__["ReflectivityBlock"], "ReflectivityBlock"));
_this.registerInput("ambientOcclusion", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("ambientOcclusion", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _ambientOcclusionBlock__WEBPACK_IMPORTED_MODULE_12__["AmbientOcclusionBlock"], "AOBlock"));
_this.registerInput("reflection", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("reflection", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _reflectionBlock__WEBPACK_IMPORTED_MODULE_18__["ReflectionBlock"], "ReflectionBlock"));
_this.registerInput("sheen", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("sheen", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _sheenBlock__WEBPACK_IMPORTED_MODULE_13__["SheenBlock"], "SheenBlock"));
_this.registerInput("clearcoat", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("clearcoat", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _clearCoatBlock__WEBPACK_IMPORTED_MODULE_19__["ClearCoatBlock"], "ClearCoatBlock"));
_this.registerInput("subsurface", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("subsurface", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _subSurfaceBlock__WEBPACK_IMPORTED_MODULE_20__["SubSurfaceBlock"], "SubSurfaceBlock"));
_this.registerInput("anisotropy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialConnectionPointCustomObject"]("anisotropy", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _anisotropyBlock__WEBPACK_IMPORTED_MODULE_17__["AnisotropyBlock"], "AnisotropyBlock"));
_this.registerOutput("ambient", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("diffuse", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("specular", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("sheenDir", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("clearcoatDir", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("diffuseInd", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("specularInd", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("sheenInd", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("clearcoatInd", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("refraction", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("lighting", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("shadow", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("alpha", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
PBRMetallicRoughnessBlock.prototype.initialize = function (state) {
state._excludeVariableName("vLightingIntensity");
state._excludeVariableName("geometricNormalW");
state._excludeVariableName("normalW");
state._excludeVariableName("faceNormal");
state._excludeVariableName("albedoOpacityOut");
state._excludeVariableName("surfaceAlbedo");
state._excludeVariableName("alpha");
state._excludeVariableName("NdotVUnclamped");
state._excludeVariableName("NdotV");
state._excludeVariableName("alphaG");
state._excludeVariableName("AARoughnessFactors");
state._excludeVariableName("environmentBrdf");
state._excludeVariableName("ambientMonochrome");
state._excludeVariableName("seo");
state._excludeVariableName("eho");
state._excludeVariableName("environmentRadiance");
state._excludeVariableName("irradianceVector");
state._excludeVariableName("environmentIrradiance");
state._excludeVariableName("diffuseBase");
state._excludeVariableName("specularBase");
state._excludeVariableName("preInfo");
state._excludeVariableName("info");
state._excludeVariableName("shadow");
state._excludeVariableName("finalDiffuse");
state._excludeVariableName("finalAmbient");
state._excludeVariableName("ambientOcclusionForDirectDiffuse");
state._excludeVariableName("finalColor");
state._excludeVariableName("vClipSpacePosition");
state._excludeVariableName("vDebugMode");
};
/**
* Gets the current class name
* @returns the class name
*/
PBRMetallicRoughnessBlock.prototype.getClassName = function () {
return "PBRMetallicRoughnessBlock";
};
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "worldNormal", {
/**
* Gets the world normal input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "perturbedNormal", {
/**
* Gets the perturbed normal input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "cameraPosition", {
/**
* Gets the camera position input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "baseColor", {
/**
* Gets the base color input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "opacityTexture", {
/**
* Gets the opacity texture input component
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "ambientColor", {
/**
* Gets the ambient color input component
*/
get: function () {
return this._inputs[6];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "reflectivity", {
/**
* Gets the reflectivity object parameters
*/
get: function () {
return this._inputs[7];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "ambientOcclusion", {
/**
* Gets the ambient occlusion object parameters
*/
get: function () {
return this._inputs[8];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "reflection", {
/**
* Gets the reflection object parameters
*/
get: function () {
return this._inputs[9];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "sheen", {
/**
* Gets the sheen object parameters
*/
get: function () {
return this._inputs[10];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "clearcoat", {
/**
* Gets the clear coat object parameters
*/
get: function () {
return this._inputs[11];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "subsurface", {
/**
* Gets the sub surface object parameters
*/
get: function () {
return this._inputs[12];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "anisotropy", {
/**
* Gets the anisotropy object parameters
*/
get: function () {
return this._inputs[13];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "ambient", {
/**
* Gets the ambient output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "diffuse", {
/**
* Gets the diffuse output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "specular", {
/**
* Gets the specular output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "sheenDir", {
/**
* Gets the sheen output component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "clearcoatDir", {
/**
* Gets the clear coat output component
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "diffuseIndirect", {
/**
* Gets the indirect diffuse output component
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "specularIndirect", {
/**
* Gets the indirect specular output component
*/
get: function () {
return this._outputs[6];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "sheenIndirect", {
/**
* Gets the indirect sheen output component
*/
get: function () {
return this._outputs[7];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "clearcoatIndirect", {
/**
* Gets the indirect clear coat output component
*/
get: function () {
return this._outputs[8];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "refraction", {
/**
* Gets the refraction output component
*/
get: function () {
return this._outputs[9];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "lighting", {
/**
* Gets the global lighting output component
*/
get: function () {
return this._outputs[10];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "shadow", {
/**
* Gets the shadow output component
*/
get: function () {
return this._outputs[11];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMetallicRoughnessBlock.prototype, "alpha", {
/**
* Gets the alpha output component
*/
get: function () {
return this._outputs[12];
},
enumerable: false,
configurable: true
});
PBRMetallicRoughnessBlock.prototype.autoConfigure = function (material) {
if (!this.cameraPosition.isConnected) {
var cameraPositionInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialSystemValues"].CameraPosition; });
if (!cameraPositionInput) {
cameraPositionInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_7__["InputBlock"]("cameraPosition");
cameraPositionInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialSystemValues"].CameraPosition);
}
cameraPositionInput.output.connectTo(this.cameraPosition);
}
};
PBRMetallicRoughnessBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
// General
defines.setValue("PBR", true);
defines.setValue("METALLICWORKFLOW", true);
defines.setValue("DEBUGMODE", this.debugMode, true);
defines.setValue("NORMALXYSCALE", true);
defines.setValue("BUMP", this.perturbedNormal.isConnected, true);
defines.setValue("LODBASEDMICROSFURACE", this._scene.getEngine().getCaps().textureLOD);
// Albedo & Opacity
defines.setValue("OPACITY", this.opacityTexture.isConnected, true);
// Lighting & colors
if (this.lightFalloff === _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD) {
defines.setValue("USEPHYSICALLIGHTFALLOFF", false);
defines.setValue("USEGLTFLIGHTFALLOFF", false);
}
else if (this.lightFalloff === _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF) {
defines.setValue("USEPHYSICALLIGHTFALLOFF", false);
defines.setValue("USEGLTFLIGHTFALLOFF", true);
}
else {
defines.setValue("USEPHYSICALLIGHTFALLOFF", true);
defines.setValue("USEGLTFLIGHTFALLOFF", false);
}
// Transparency
defines.setValue("ALPHABLEND", this.useAlphaBlending, true);
defines.setValue("ALPHAFROMALBEDO", this.useAlphaFromAlbedoTexture, true);
defines.setValue("ALPHATEST", this.useAlphaTest, true);
defines.setValue("ALPHATESTVALUE", this.alphaTestCutoff, true);
defines.setValue("OPACITYRGB", this.opacityRGB, true);
// Rendering
defines.setValue("RADIANCEOVERALPHA", this.useRadianceOverAlpha, true);
defines.setValue("SPECULAROVERALPHA", this.useSpecularOverAlpha, true);
defines.setValue("SPECULARAA", this._scene.getEngine().getCaps().standardDerivatives && this.enableSpecularAntiAliasing, true);
defines.setValue("REALTIME_FILTERING", this.realTimeFiltering, true);
defines.setValue("NUM_SAMPLES", "" + this.realTimeFilteringQuality, true);
if (this._scene.getEngine().webGLVersion > 1) {
defines.setValue("NUM_SAMPLES", this.realTimeFilteringQuality + "u", true);
}
// Advanced
defines.setValue("BRDF_V_HEIGHT_CORRELATED", true);
defines.setValue("MS_BRDF_ENERGY_CONSERVATION", this.useEnergyConservation, true);
defines.setValue("RADIANCEOCCLUSION", this.useRadianceOcclusion, true);
defines.setValue("HORIZONOCCLUSION", this.useHorizonOcclusion, true);
defines.setValue("UNLIT", this.unlit, true);
defines.setValue("FORCENORMALFORWARD", this.forceNormalForward, true);
if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_16__["MaterialFlags"].ReflectionTextureEnabled) {
defines.setValue("ENVIRONMENTBRDF", true);
defines.setValue("ENVIRONMENTBRDF_RGBD", this._environmentBRDFTexture.isRGBD, true);
}
else {
defines.setValue("ENVIRONMENTBRDF", false);
defines.setValue("ENVIRONMENTBRDF_RGBD", false);
}
if (!defines._areLightsDirty) {
return;
}
var scene = mesh.getScene();
if (!this.light) {
// Lights
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, true, nodeMaterial.maxSimultaneousLights);
defines._needNormals = true;
// Multiview
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines);
}
else {
var state = {
needNormals: false,
needRebuild: false,
lightmapMode: false,
shadowEnabled: false,
specularEnabled: false
};
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForLight(scene, mesh, this.light, this._lightId, defines, true, state);
if (state.needRebuild) {
defines.rebuild();
}
}
};
PBRMetallicRoughnessBlock.prototype.updateUniformsAndSamples = function (state, nodeMaterial, defines, uniformBuffers) {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareUniformsAndSamplersList({
uniformsNames: state.uniforms,
uniformBuffersNames: uniformBuffers,
samplers: state.samplers,
defines: defines,
maxSimultaneousLights: nodeMaterial.maxSimultaneousLights
});
};
PBRMetallicRoughnessBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (!mesh) {
return;
}
var scene = mesh.getScene();
if (!this.light) {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindLights(scene, mesh, effect, true, nodeMaterial.maxSimultaneousLights);
}
else {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindLight(this.light, this._lightId, scene, effect, true);
}
effect.setTexture(this._environmentBrdfSamplerName, this._environmentBRDFTexture);
effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor);
var ambientScene = this._scene.ambientColor;
if (ambientScene) {
effect.setColor3("ambientFromScene", ambientScene);
}
var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
effect.setFloat(this._invertNormalName, invertNormal ? -1 : 1);
effect.setFloat4("vLightingIntensity", this.directIntensity, 1, this.environmentIntensity * this._scene.environmentIntensity, this.specularIntensity);
};
PBRMetallicRoughnessBlock.prototype._injectVertexCode = function (state) {
var _a, _b;
var worldPos = this.worldPosition;
var comments = "//" + this.name;
// Declaration
if (!this.light) { // Emit for all lights
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
repeatKey: "maxSimultaneousLights"
});
this._lightId = 0;
state.sharedData.dynamicUniformBlocks.push(this);
}
else {
this._lightId = (state.counters["lightCounter"] !== undefined ? state.counters["lightCounter"] : -1) + 1;
state.counters["lightCounter"] = this._lightId;
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
}, this._lightId.toString());
}
// Inject code in vertex
var worldPosVaryingName = "v_" + worldPos.associatedVariableName;
if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
state.compilationString += worldPosVaryingName + " = " + worldPos.associatedVariableName + ";\r\n";
}
var reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null;
state.compilationString += (_b = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.handleVertexSide(state)) !== null && _b !== void 0 ? _b : "";
state._emitUniformFromString("vDebugMode", "vec2", "defined(IGNORE) || DEBUGMODE > 0");
state._emitUniformFromString("ambientFromScene", "vec3");
if (state._emitVaryingFromString("vClipSpacePosition", "vec4", "defined(IGNORE) || DEBUGMODE > 0")) {
state._injectAtEnd += "#if DEBUGMODE > 0\r\n";
state._injectAtEnd += "vClipSpacePosition = gl_Position;\r\n";
state._injectAtEnd += "#endif\r\n";
}
if (this.light) {
state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
replaceStrings: [
{ search: /{X}/g, replace: this._lightId.toString() },
{ search: /worldPos/g, replace: worldPos.associatedVariableName }
]
});
}
else {
state.compilationString += "vec4 worldPos = " + worldPos.associatedVariableName + ";\r\n";
state.compilationString += state._emitCodeFromInclude("shadowsVertex", comments, {
repeatKey: "maxSimultaneousLights"
});
}
};
/**
* Gets the code corresponding to the albedo/opacity module
* @returns the shader code
*/
PBRMetallicRoughnessBlock.prototype.getAlbedoOpacityCode = function () {
var code = "albedoOpacityOutParams albedoOpacityOut;\r\n";
var albedoColor = this.baseColor.isConnected ? this.baseColor.associatedVariableName : "vec4(1., 1., 1., 1.)";
var opacityTexture = this.opacityTexture.isConnected ? this.opacityTexture.associatedVariableName : "";
code += "albedoOpacityBlock(\n " + albedoColor + ",\n #ifdef ALBEDO\n vec4(1.),\n vec2(1., 1.),\n #endif\n #ifdef OPACITY\n " + opacityTexture + ",\n vec2(1., 1.),\n #endif\n albedoOpacityOut\n );\n\n vec3 surfaceAlbedo = albedoOpacityOut.surfaceAlbedo;\n float alpha = albedoOpacityOut.alpha;\r\n";
return code;
};
PBRMetallicRoughnessBlock.prototype._buildBlock = function (state) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19;
_super.prototype._buildBlock.call(this, state);
this._scene = state.sharedData.scene;
if (!this._environmentBRDFTexture) {
this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_15__["BRDFTextureTools"].GetEnvironmentBRDFTexture(this._scene);
}
var reflectionBlock = this.reflection.isConnected ? (_a = this.reflection.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null;
if (reflectionBlock) {
// Need those variables to be setup when calling _injectVertexCode
reflectionBlock.worldPositionConnectionPoint = this.worldPosition;
reflectionBlock.cameraPositionConnectionPoint = this.cameraPosition;
reflectionBlock.worldNormalConnectionPoint = this.worldNormal;
}
if (state.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment) {
// Vertex
this._injectVertexCode(state);
return this;
}
// Fragment
state.sharedData.bindableBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
var comments = "//" + this.name;
var worldPosVarName = "v_" + this.worldPosition.associatedVariableName;
var normalShading = this.perturbedNormal;
this._environmentBrdfSamplerName = state._getFreeVariableName("environmentBrdfSampler");
state._emit2DSampler(this._environmentBrdfSamplerName);
state.sharedData.hints.needAlphaBlending = state.sharedData.hints.needAlphaBlending || this.useAlphaBlending;
state.sharedData.hints.needAlphaTesting = state.sharedData.hints.needAlphaTesting || this.useAlphaTest;
state._emitExtension("lod", "#extension GL_EXT_shader_texture_lod : enable", "defined(LODBASEDMICROSFURACE)");
//
// Includes
//
if (!this.light) { // Emit for all lights
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
repeatKey: "maxSimultaneousLights"
});
}
else {
state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", comments, {
replaceStrings: [{ search: /{X}/g, replace: this._lightId.toString() }]
}, this._lightId.toString());
}
state._emitFunctionFromInclude("helperFunctions", comments);
state._emitFunctionFromInclude("importanceSampling", comments);
state._emitFunctionFromInclude("pbrHelperFunctions", comments);
state._emitFunctionFromInclude("imageProcessingFunctions", comments);
state._emitFunctionFromInclude("shadowsFragmentFunctions", comments, {
replaceStrings: [
{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" }
]
});
state._emitFunctionFromInclude("pbrDirectLightingSetupFunctions", comments, {
replaceStrings: [
{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" }
]
});
state._emitFunctionFromInclude("pbrDirectLightingFalloffFunctions", comments);
state._emitFunctionFromInclude("pbrBRDFFunctions", comments);
state._emitFunctionFromInclude("hdrFilteringFunctions", comments);
state._emitFunctionFromInclude("pbrDirectLightingFunctions", comments, {
replaceStrings: [
{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" }
]
});
state._emitFunctionFromInclude("pbrIBLFunctions", comments);
state._emitFunctionFromInclude("pbrBlockAlbedoOpacity", comments);
state._emitFunctionFromInclude("pbrBlockReflectivity", comments);
state._emitFunctionFromInclude("pbrBlockAmbientOcclusion", comments);
state._emitFunctionFromInclude("pbrBlockAlphaFresnel", comments);
state._emitFunctionFromInclude("pbrBlockAnisotropic", comments);
//
// code
//
state._emitUniformFromString("vLightingIntensity", "vec4");
// _____________________________ Geometry Information ____________________________
this._vNormalWName = state._getFreeVariableName("vNormalW");
state.compilationString += "vec4 " + this._vNormalWName + " = normalize(" + this.worldNormal.associatedVariableName + ");\r\n";
if (state._registerTempVariable("viewDirectionW")) {
state.compilationString += "vec3 viewDirectionW = normalize(" + this.cameraPosition.associatedVariableName + " - " + worldPosVarName + ".xyz);\r\n";
}
state.compilationString += "vec3 geometricNormalW = " + this._vNormalWName + ".xyz;\r\n";
state.compilationString += "vec3 normalW = " + (normalShading.isConnected ? "normalize(" + normalShading.associatedVariableName + ".xyz)" : "geometricNormalW") + ";\r\n";
this._invertNormalName = state._getFreeVariableName("invertNormal");
state._emitUniformFromString(this._invertNormalName, "float");
state.compilationString += state._emitCodeFromInclude("pbrBlockNormalFinal", comments, {
replaceStrings: [
{ search: /vPositionW/g, replace: worldPosVarName + ".xyz" },
{ search: /vEyePosition.w/g, replace: this._invertNormalName },
]
});
// _____________________________ Albedo & Opacity ______________________________
state.compilationString += this.getAlbedoOpacityCode();
state.compilationString += state._emitCodeFromInclude("depthPrePass", comments);
// _____________________________ AO _______________________________
var aoBlock = (_b = this.ambientOcclusion.connectedPoint) === null || _b === void 0 ? void 0 : _b.ownerBlock;
state.compilationString += _ambientOcclusionBlock__WEBPACK_IMPORTED_MODULE_12__["AmbientOcclusionBlock"].GetCode(aoBlock);
state.compilationString += state._emitCodeFromInclude("pbrBlockLightmapInit", comments);
// _____________________________ UNLIT _______________________________
state.compilationString += "#ifdef UNLIT\n vec3 diffuseBase = vec3(1., 1., 1.);\n #else\r\n";
// _____________________________ Reflectivity _______________________________
var subsurfaceBlock = this.subsurface.isConnected ? (_c = this.subsurface.connectedPoint) === null || _c === void 0 ? void 0 : _c.ownerBlock : null;
var refractionBlock = this.subsurface.isConnected ? (_e = ((_d = this.subsurface.connectedPoint) === null || _d === void 0 ? void 0 : _d.ownerBlock).refraction.connectedPoint) === null || _e === void 0 ? void 0 : _e.ownerBlock : null;
var reflectivityBlock = (_g = (_f = this.reflectivity.connectedPoint) === null || _f === void 0 ? void 0 : _f.ownerBlock) !== null && _g !== void 0 ? _g : null;
if (reflectivityBlock) {
reflectivityBlock.indexOfRefractionConnectionPoint = (_h = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.indexOfRefraction) !== null && _h !== void 0 ? _h : null;
}
var aoIntensity = (aoBlock === null || aoBlock === void 0 ? void 0 : aoBlock.intensity.isConnected) ? aoBlock.intensity.associatedVariableName : "1.";
state.compilationString += (_j = reflectivityBlock === null || reflectivityBlock === void 0 ? void 0 : reflectivityBlock.getCode(state, aoIntensity)) !== null && _j !== void 0 ? _j : "";
// _____________________________ Geometry info _________________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockGeometryInfo", comments, {
replaceStrings: [
{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_k = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _k !== void 0 ? _k : "REFLECTIONMAP_SKYBOX" },
{ search: /REFLECTIONMAP_3D/g, replace: (_l = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _l !== void 0 ? _l : "REFLECTIONMAP_3D" },
]
});
// _____________________________ Anisotropy _______________________________________
var anisotropyBlock = this.anisotropy.isConnected ? (_m = this.anisotropy.connectedPoint) === null || _m === void 0 ? void 0 : _m.ownerBlock : null;
if (anisotropyBlock) {
anisotropyBlock.worldPositionConnectionPoint = this.worldPosition;
anisotropyBlock.worldNormalConnectionPoint = this.worldNormal;
state.compilationString += anisotropyBlock.getCode(state, !this.perturbedNormal.isConnected);
}
// _____________________________ Reflection _______________________________________
if (reflectionBlock && reflectionBlock.hasTexture) {
state.compilationString += reflectionBlock.getCode(state, anisotropyBlock ? "anisotropicOut.anisotropicNormal" : "normalW");
}
state._emitFunctionFromInclude("pbrBlockReflection", comments, {
replaceStrings: [
{ search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" },
{ search: /REFLECTIONMAP_3D/g, replace: (_o = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _o !== void 0 ? _o : "REFLECTIONMAP_3D" },
{ search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_p = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _p !== void 0 ? _p : "REFLECTIONMAP_OPPOSITEZ" },
{ search: /REFLECTIONMAP_PROJECTION/g, replace: (_q = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _q !== void 0 ? _q : "REFLECTIONMAP_PROJECTION" },
{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_r = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _r !== void 0 ? _r : "REFLECTIONMAP_SKYBOX" },
{ search: /LODINREFLECTIONALPHA/g, replace: (_s = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _s !== void 0 ? _s : "LODINREFLECTIONALPHA" },
{ search: /LINEARSPECULARREFLECTION/g, replace: (_t = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _t !== void 0 ? _t : "LINEARSPECULARREFLECTION" },
{ search: /vReflectionFilteringInfo/g, replace: (_u = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionFilteringInfoName) !== null && _u !== void 0 ? _u : "vReflectionFilteringInfo" },
]
});
// ___________________ Compute Reflectance aka R0 F0 info _________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance0", comments, {
replaceStrings: [
{ search: /metallicReflectanceFactors/g, replace: (_v = reflectivityBlock === null || reflectivityBlock === void 0 ? void 0 : reflectivityBlock._vMetallicReflectanceFactorsName) !== null && _v !== void 0 ? _v : "metallicReflectanceFactors" },
]
});
// ________________________________ Sheen ______________________________
var sheenBlock = this.sheen.isConnected ? (_w = this.sheen.connectedPoint) === null || _w === void 0 ? void 0 : _w.ownerBlock : null;
if (sheenBlock) {
state.compilationString += sheenBlock.getCode(reflectionBlock);
}
state._emitFunctionFromInclude("pbrBlockSheen", comments, {
replaceStrings: [
{ search: /REFLECTIONMAP_3D/g, replace: (_x = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _x !== void 0 ? _x : "REFLECTIONMAP_3D" },
{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_y = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _y !== void 0 ? _y : "REFLECTIONMAP_SKYBOX" },
{ search: /LODINREFLECTIONALPHA/g, replace: (_z = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _z !== void 0 ? _z : "LODINREFLECTIONALPHA" },
{ search: /LINEARSPECULARREFLECTION/g, replace: (_0 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _0 !== void 0 ? _0 : "LINEARSPECULARREFLECTION" },
]
});
// _____________________________ Clear Coat ____________________________
var clearcoatBlock = this.clearcoat.isConnected ? (_1 = this.clearcoat.connectedPoint) === null || _1 === void 0 ? void 0 : _1.ownerBlock : null;
var generateTBNSpace = !this.perturbedNormal.isConnected && !this.anisotropy.isConnected;
var isTangentConnectedToPerturbNormal = this.perturbedNormal.isConnected && ((_2 = this.perturbedNormal.connectedPoint) === null || _2 === void 0 ? void 0 : _2.ownerBlock).worldTangent.isConnected;
var isTangentConnectedToAnisotropy = this.anisotropy.isConnected && ((_3 = this.anisotropy.connectedPoint) === null || _3 === void 0 ? void 0 : _3.ownerBlock).worldTangent.isConnected;
var vTBNAvailable = isTangentConnectedToPerturbNormal || (!this.perturbedNormal.isConnected && isTangentConnectedToAnisotropy);
state.compilationString += _clearCoatBlock__WEBPACK_IMPORTED_MODULE_19__["ClearCoatBlock"].GetCode(state, clearcoatBlock, reflectionBlock, worldPosVarName, generateTBNSpace, vTBNAvailable, this.worldNormal.associatedVariableName);
if (generateTBNSpace) {
vTBNAvailable = (_4 = clearcoatBlock === null || clearcoatBlock === void 0 ? void 0 : clearcoatBlock.worldTangent.isConnected) !== null && _4 !== void 0 ? _4 : false;
}
state._emitFunctionFromInclude("pbrBlockClearcoat", comments, {
replaceStrings: [
{ search: /computeReflectionCoords/g, replace: "computeReflectionCoordsPBR" },
{ search: /REFLECTIONMAP_3D/g, replace: (_5 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _5 !== void 0 ? _5 : "REFLECTIONMAP_3D" },
{ search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_6 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _6 !== void 0 ? _6 : "REFLECTIONMAP_OPPOSITEZ" },
{ search: /REFLECTIONMAP_PROJECTION/g, replace: (_7 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _7 !== void 0 ? _7 : "REFLECTIONMAP_PROJECTION" },
{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_8 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _8 !== void 0 ? _8 : "REFLECTIONMAP_SKYBOX" },
{ search: /LODINREFLECTIONALPHA/g, replace: (_9 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLODReflectionAlpha) !== null && _9 !== void 0 ? _9 : "LODINREFLECTIONALPHA" },
{ search: /LINEARSPECULARREFLECTION/g, replace: (_10 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineLinearSpecularReflection) !== null && _10 !== void 0 ? _10 : "LINEARSPECULARREFLECTION" },
{ search: /defined\(TANGENT\)/g, replace: vTBNAvailable ? "defined(TANGENT)" : "defined(IGNORE)" },
]
});
// _________________________ Specular Environment Reflectance __________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockReflectance", comments, {
replaceStrings: [
{ search: /REFLECTIONMAP_SKYBOX/g, replace: (_11 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) !== null && _11 !== void 0 ? _11 : "REFLECTIONMAP_SKYBOX" },
{ search: /REFLECTIONMAP_3D/g, replace: (_12 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _12 !== void 0 ? _12 : "REFLECTIONMAP_3D" },
]
});
// ___________________________________ SubSurface ______________________________________
state.compilationString += _subSurfaceBlock__WEBPACK_IMPORTED_MODULE_20__["SubSurfaceBlock"].GetCode(state, subsurfaceBlock, reflectionBlock, worldPosVarName);
state._emitFunctionFromInclude("pbrBlockSubSurface", comments, {
replaceStrings: [
{ search: /REFLECTIONMAP_3D/g, replace: (_13 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) !== null && _13 !== void 0 ? _13 : "REFLECTIONMAP_3D" },
{ search: /REFLECTIONMAP_OPPOSITEZ/g, replace: (_14 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineOppositeZ) !== null && _14 !== void 0 ? _14 : "REFLECTIONMAP_OPPOSITEZ" },
{ search: /REFLECTIONMAP_PROJECTION/g, replace: (_15 = reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineProjectionName) !== null && _15 !== void 0 ? _15 : "REFLECTIONMAP_PROJECTION" },
{ search: /SS_REFRACTIONMAP_3D/g, replace: (_16 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _16 !== void 0 ? _16 : "SS_REFRACTIONMAP_3D" },
{ search: /SS_LODINREFRACTIONALPHA/g, replace: (_17 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _17 !== void 0 ? _17 : "SS_LODINREFRACTIONALPHA" },
{ search: /SS_LINEARSPECULARREFRACTION/g, replace: (_18 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _18 !== void 0 ? _18 : "SS_LINEARSPECULARREFRACTION" },
{ search: /SS_REFRACTIONMAP_OPPOSITEZ/g, replace: (_19 = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineOppositeZ) !== null && _19 !== void 0 ? _19 : "SS_REFRACTIONMAP_OPPOSITEZ" },
]
});
// _____________________________ Direct Lighting Info __________________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockDirectLighting", comments);
if (this.light) {
state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
replaceStrings: [
{ search: /{X}/g, replace: this._lightId.toString() }
]
});
}
else {
state.compilationString += state._emitCodeFromInclude("lightFragment", comments, {
repeatKey: "maxSimultaneousLights"
});
}
// _____________________________ Compute Final Lit Components ________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockFinalLitComponents", comments);
// _____________________________ UNLIT (2) ________________________
state.compilationString += "#endif\r\n"; // UNLIT
// _____________________________ Compute Final Unlit Components ________________________
var aoColor = this.ambientColor.isConnected ? this.ambientColor.associatedVariableName : "vec3(0., 0., 0.)";
var aoDirectLightIntensity = (aoBlock === null || aoBlock === void 0 ? void 0 : aoBlock.directLightIntensity.isConnected) ? aoBlock.directLightIntensity.associatedVariableName : _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"].DEFAULT_AO_ON_ANALYTICAL_LIGHTS.toString();
if (!(aoBlock === null || aoBlock === void 0 ? void 0 : aoBlock.directLightIntensity.isConnected) && aoDirectLightIntensity.indexOf('.') === -1) {
aoDirectLightIntensity += ".";
}
state.compilationString += state._emitCodeFromInclude("pbrBlockFinalUnlitComponents", comments, {
replaceStrings: [
{ search: /vec3 finalEmissive[\s\S]*?finalEmissive\*=vLightingIntensity\.y;/g, replace: "" },
{ search: /vAmbientColor/g, replace: aoColor + " * ambientFromScene" },
{ search: /vAmbientInfos\.w/g, replace: aoDirectLightIntensity },
]
});
// _____________________________ Output Final Color Composition ________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockFinalColorComposition", comments, {
replaceStrings: [
{ search: /finalEmissive/g, replace: "vec3(0.)" },
]
});
// _____________________________ Apply image processing ________________________
state.compilationString += state._emitCodeFromInclude("pbrBlockImageProcessing", comments, {
replaceStrings: [
{ search: /visibility/g, replace: "1." },
]
});
// _____________________________ Generate debug code ________________________
state.compilationString += state._emitCodeFromInclude("pbrDebug", comments, {
replaceStrings: [
{ search: /vNormalW/g, replace: this._vNormalWName },
{ search: /vPositionW/g, replace: worldPosVarName },
{ search: /albedoTexture\.rgb;/g, replace: "vec3(1.);\r\ngl_FragColor.rgb = toGammaSpace(gl_FragColor.rgb);\r\n" },
{ search: /opacityMap/g, replace: this.opacityTexture.associatedVariableName },
]
});
// _____________________________ Generate end points ________________________
for (var _i = 0, _20 = this._outputs; _i < _20.length; _i++) {
var output = _20[_i];
if (output.hasEndpoints) {
var remap = mapOutputToVariable[output.name];
if (remap) {
var varName = remap[0], conditions = remap[1];
if (conditions) {
state.compilationString += "#if " + conditions + "\r\n";
}
state.compilationString += this._declareOutput(output, state) + " = " + varName + ";\r\n";
if (conditions) {
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(output, state) + " = vec3(0.);\r\n";
state.compilationString += "#endif\r\n";
}
}
else {
console.error("There's no remapping for the " + output.name + " end point! No code generated");
}
}
}
return this;
};
PBRMetallicRoughnessBlock.prototype._dumpPropertiesCode = function () {
var codeString = "";
codeString += this._codeVariableName + ".lightFalloff = " + this.lightFalloff + ";\r\n";
codeString += this._codeVariableName + ".useAlphaFromAlbedoTexture = " + this.useAlphaFromAlbedoTexture + ";\r\n";
codeString += this._codeVariableName + ".useAlphaTest = " + this.useAlphaTest + ";\r\n";
codeString += this._codeVariableName + ".alphaTestCutoff = " + this.alphaTestCutoff + ";\r\n";
codeString += this._codeVariableName + ".useAlphaBlending = " + this.useAlphaBlending + ";\r\n";
codeString += this._codeVariableName + ".opacityRGB = " + this.opacityRGB + ";\r\n";
codeString += this._codeVariableName + ".useRadianceOverAlpha = " + this.useRadianceOverAlpha + ";\r\n";
codeString += this._codeVariableName + ".useSpecularOverAlpha = " + this.useSpecularOverAlpha + ";\r\n";
codeString += this._codeVariableName + ".enableSpecularAntiAliasing = " + this.enableSpecularAntiAliasing + ";\r\n";
codeString += this._codeVariableName + ".realTimeFiltering = " + this.realTimeFiltering + ";\r\n";
codeString += this._codeVariableName + ".realTimeFilteringQuality = " + this.realTimeFilteringQuality + ";\r\n";
codeString += this._codeVariableName + ".useEnergyConservation = " + this.useEnergyConservation + ";\r\n";
codeString += this._codeVariableName + ".useRadianceOcclusion = " + this.useRadianceOcclusion + ";\r\n";
codeString += this._codeVariableName + ".useHorizonOcclusion = " + this.useHorizonOcclusion + ";\r\n";
codeString += this._codeVariableName + ".unlit = " + this.unlit + ";\r\n";
codeString += this._codeVariableName + ".forceNormalForward = " + this.forceNormalForward + ";\r\n";
codeString += this._codeVariableName + ".debugMode = " + this.debugMode + ";\r\n";
codeString += this._codeVariableName + ".debugLimit = " + this.debugLimit + ";\r\n";
codeString += this._codeVariableName + ".debugFactor = " + this.debugFactor + ";\r\n";
return codeString;
};
PBRMetallicRoughnessBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
if (this.light) {
serializationObject.lightId = this.light.id;
}
serializationObject.lightFalloff = this.lightFalloff;
serializationObject.useAlphaFromAlbedoTexture = this.useAlphaFromAlbedoTexture;
serializationObject.useAlphaTest = this.useAlphaTest;
serializationObject.alphaTestCutoff = this.alphaTestCutoff;
serializationObject.useAlphaBlending = this.useAlphaBlending;
serializationObject.opacityRGB = this.opacityRGB;
serializationObject.useRadianceOverAlpha = this.useRadianceOverAlpha;
serializationObject.useSpecularOverAlpha = this.useSpecularOverAlpha;
serializationObject.enableSpecularAntiAliasing = this.enableSpecularAntiAliasing;
serializationObject.realTimeFiltering = this.realTimeFiltering;
serializationObject.realTimeFilteringQuality = this.realTimeFilteringQuality;
serializationObject.useEnergyConservation = this.useEnergyConservation;
serializationObject.useRadianceOcclusion = this.useRadianceOcclusion;
serializationObject.useHorizonOcclusion = this.useHorizonOcclusion;
serializationObject.unlit = this.unlit;
serializationObject.forceNormalForward = this.forceNormalForward;
serializationObject.debugMode = this.debugMode;
serializationObject.debugLimit = this.debugLimit;
serializationObject.debugFactor = this.debugFactor;
return serializationObject;
};
PBRMetallicRoughnessBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
var _a, _b;
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
if (serializationObject.lightId) {
this.light = scene.getLightByID(serializationObject.lightId);
}
this.lightFalloff = (_a = serializationObject.lightFalloff) !== null && _a !== void 0 ? _a : 0;
this.useAlphaFromAlbedoTexture = serializationObject.useAlphaFromAlbedoTexture;
this.useAlphaTest = serializationObject.useAlphaTest;
this.alphaTestCutoff = serializationObject.alphaTestCutoff;
this.useAlphaBlending = serializationObject.useAlphaBlending;
this.opacityRGB = serializationObject.opacityRGB;
this.useRadianceOverAlpha = serializationObject.useRadianceOverAlpha;
this.useSpecularOverAlpha = serializationObject.useSpecularOverAlpha;
this.enableSpecularAntiAliasing = serializationObject.enableSpecularAntiAliasing;
this.realTimeFiltering = !!serializationObject.realTimeFiltering;
this.realTimeFilteringQuality = (_b = serializationObject.realTimeFilteringQuality) !== null && _b !== void 0 ? _b : _Engines_constants__WEBPACK_IMPORTED_MODULE_21__["Constants"].TEXTURE_FILTERING_QUALITY_LOW;
this.useEnergyConservation = serializationObject.useEnergyConservation;
this.useRadianceOcclusion = serializationObject.useRadianceOcclusion;
this.useHorizonOcclusion = serializationObject.useHorizonOcclusion;
this.unlit = serializationObject.unlit;
this.forceNormalForward = !!serializationObject.forceNormalForward;
this.debugMode = serializationObject.debugMode;
this.debugLimit = serializationObject.debugLimit;
this.debugFactor = serializationObject.debugFactor;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Direct lights", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Float, "INTENSITY", { min: 0, max: 1, "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "directIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Environment lights", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Float, "INTENSITY", { min: 0, max: 1, "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "environmentIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Specular highlights", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Float, "INTENSITY", { min: 0, max: 1, "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "specularIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Light falloff", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].List, "LIGHTING & COLORS", { "notifiers": { "update": true }, "options": [
{ label: "Physical", value: _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL },
{ label: "GLTF", value: _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF },
{ label: "Standard", value: _PBR_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_9__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD },
] })
], PBRMetallicRoughnessBlock.prototype, "lightFalloff", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Alpha from albedo", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "TRANSPARENCY", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "useAlphaFromAlbedoTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Alpha Testing", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "TRANSPARENCY")
], PBRMetallicRoughnessBlock.prototype, "useAlphaTest", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Alpha CutOff", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Float, "TRANSPARENCY", { min: 0, max: 1, "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "alphaTestCutoff", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Alpha blending", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "TRANSPARENCY")
], PBRMetallicRoughnessBlock.prototype, "useAlphaBlending", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Get alpha from opacity texture RGB", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "TRANSPARENCY", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "opacityRGB", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Radiance over alpha", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "RENDERING", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "useRadianceOverAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Specular over alpha", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "RENDERING", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "useSpecularOverAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Specular anti-aliasing", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "RENDERING", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "enableSpecularAntiAliasing", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Realtime filtering", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "RENDERING", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "realTimeFiltering", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Realtime filtering quality", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].List, "RENDERING", { "notifiers": { "update": true }, "options": [
{ label: "Low", value: _Engines_constants__WEBPACK_IMPORTED_MODULE_21__["Constants"].TEXTURE_FILTERING_QUALITY_LOW },
{ label: "Medium", value: _Engines_constants__WEBPACK_IMPORTED_MODULE_21__["Constants"].TEXTURE_FILTERING_QUALITY_MEDIUM },
{ label: "High", value: _Engines_constants__WEBPACK_IMPORTED_MODULE_21__["Constants"].TEXTURE_FILTERING_QUALITY_HIGH },
] })
], PBRMetallicRoughnessBlock.prototype, "realTimeFilteringQuality", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Energy Conservation", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "useEnergyConservation", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Radiance occlusion", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "useRadianceOcclusion", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Horizon occlusion", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "useHorizonOcclusion", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Unlit", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "unlit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Force normal forward", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "forceNormalForward", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Debug mode", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].List, "DEBUG", { "notifiers": { "update": true }, "options": [
{ label: "None", value: 0 },
// Geometry
{ label: "Normalized position", value: 1 },
{ label: "Normals", value: 2 },
{ label: "Tangents", value: 3 },
{ label: "Bitangents", value: 4 },
{ label: "Bump Normals", value: 5 },
//{ label: "UV1", value: 6 },
//{ label: "UV2", value: 7 },
{ label: "ClearCoat Normals", value: 8 },
{ label: "ClearCoat Tangents", value: 9 },
{ label: "ClearCoat Bitangents", value: 10 },
{ label: "Anisotropic Normals", value: 11 },
{ label: "Anisotropic Tangents", value: 12 },
{ label: "Anisotropic Bitangents", value: 13 },
// Maps
{ label: "Albedo Map", value: 20 },
{ label: "Ambient Map", value: 21 },
{ label: "Opacity Map", value: 22 },
//{ label: "Emissive Map", value: 23 },
//{ label: "Light Map", value: 24 },
{ label: "Metallic Map", value: 25 },
{ label: "Reflectivity Map", value: 26 },
{ label: "ClearCoat Map", value: 27 },
{ label: "ClearCoat Tint Map", value: 28 },
{ label: "Sheen Map", value: 29 },
{ label: "Anisotropic Map", value: 30 },
{ label: "Thickness Map", value: 31 },
// Env
{ label: "Env Refraction", value: 40 },
{ label: "Env Reflection", value: 41 },
{ label: "Env Clear Coat", value: 42 },
// Lighting
{ label: "Direct Diffuse", value: 50 },
{ label: "Direct Specular", value: 51 },
{ label: "Direct Clear Coat", value: 52 },
{ label: "Direct Sheen", value: 53 },
{ label: "Env Irradiance", value: 54 },
// Lighting Params
{ label: "Surface Albedo", value: 60 },
{ label: "Reflectance 0", value: 61 },
{ label: "Metallic", value: 62 },
{ label: "Metallic F0", value: 71 },
{ label: "Roughness", value: 63 },
{ label: "AlphaG", value: 64 },
{ label: "NdotV", value: 65 },
{ label: "ClearCoat Color", value: 66 },
{ label: "ClearCoat Roughness", value: 67 },
{ label: "ClearCoat NdotV", value: 68 },
{ label: "Transmittance", value: 69 },
{ label: "Refraction Transmittance", value: 70 },
// Misc
{ label: "SEO", value: 80 },
{ label: "EHO", value: 81 },
{ label: "Energy Factor", value: 82 },
{ label: "Specular Reflectance", value: 83 },
{ label: "Clear Coat Reflectance", value: 84 },
{ label: "Sheen Reflectance", value: 85 },
{ label: "Luminance Over Alpha", value: 86 },
{ label: "Alpha", value: 87 },
] })
], PBRMetallicRoughnessBlock.prototype, "debugMode", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Split position", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Float, "DEBUG", { min: -1, max: 1, "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "debugLimit", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["editableInPropertyPage"])("Output factor", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_10__["PropertyTypeForEdition"].Float, "DEBUG", { min: 0, max: 5, "notifiers": { "update": true } })
], PBRMetallicRoughnessBlock.prototype, "debugFactor", void 0);
return PBRMetallicRoughnessBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_8__["_TypeStore"].RegisteredTypes["BABYLON.PBRMetallicRoughnessBlock"] = PBRMetallicRoughnessBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/reflectionBlock.ts":
/*!******************************************************!*\
!*** ./Materials/Node/Blocks/PBR/reflectionBlock.ts ***!
\******************************************************/
/*! exports provided: ReflectionBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectionBlock", function() { return ReflectionBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/* harmony import */ var _Dual_reflectionTextureBaseBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Dual/reflectionTextureBaseBlock */ "./Materials/Node/Blocks/Dual/reflectionTextureBaseBlock.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../../Maths/math.scalar */ "./Maths/math.scalar.ts");
/**
* Block used to implement the reflection module of the PBR material
*/
var ReflectionBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReflectionBlock, _super);
/**
* Create a new ReflectionBlock
* @param name defines the block name
*/
function ReflectionBlock(name) {
var _this = _super.call(this, name) || this;
/**
* Defines if the material uses spherical harmonics vs spherical polynomials for the
* diffuse part of the IBL.
*/
_this.useSphericalHarmonics = true;
/**
* Force the shader to compute irradiance in the fragment shader in order to take bump in account.
*/
_this.forceIrradianceInFragment = false;
_this._isUnique = true;
_this.registerInput("position", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Vector3, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("world", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex);
_this.registerInput("view", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("reflection", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialConnectionPointCustomObject"]("reflection", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialConnectionPointDirection"].Output, ReflectionBlock, "ReflectionBlock"));
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ReflectionBlock.prototype.getClassName = function () {
return "ReflectionBlock";
};
Object.defineProperty(ReflectionBlock.prototype, "position", {
/**
* Gets the position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this.worldPositionConnectionPoint;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "worldNormal", {
/**
* Gets the world normal input component
*/
get: function () {
return this.worldNormalConnectionPoint;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "world", {
/**
* Gets the world input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "cameraPosition", {
/**
* Gets the camera (or eye) position component
*/
get: function () {
return this.cameraPositionConnectionPoint;
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "view", {
/**
* Gets the view input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "color", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "reflection", {
/**
* Gets the reflection object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "hasTexture", {
/**
* Returns true if the block has a texture (either its own texture or the environment texture from the scene, if set)
*/
get: function () {
return !!this._getTexture();
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectionBlock.prototype, "reflectionColor", {
/**
* Gets the reflection color (either the name of the variable if the color input is connected, else a default value)
*/
get: function () {
return this.color.isConnected ? this.color.associatedVariableName : "vec3(1., 1., 1.)";
},
enumerable: false,
configurable: true
});
ReflectionBlock.prototype._getTexture = function () {
if (this.texture) {
return this.texture;
}
return this._scene.environmentTexture;
};
ReflectionBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
var reflectionTexture = this._getTexture();
var reflection = reflectionTexture && reflectionTexture.getTextureMatrix;
defines.setValue("REFLECTION", reflection, true);
if (!reflection) {
return;
}
defines.setValue(this._defineLODReflectionAlpha, reflectionTexture.lodLevelInAlpha, true);
defines.setValue(this._defineLinearSpecularReflection, reflectionTexture.linearSpecularLOD, true);
defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ, true);
defines.setValue("SPHERICAL_HARMONICS", this.useSphericalHarmonics, true);
defines.setValue("GAMMAREFLECTION", reflectionTexture.gammaSpace, true);
defines.setValue("RGBDREFLECTION", reflectionTexture.isRGBD, true);
if (reflectionTexture && reflectionTexture.coordinatesMode !== _Textures_texture__WEBPACK_IMPORTED_MODULE_7__["Texture"].SKYBOX_MODE) {
if (reflectionTexture.isCube) {
defines.setValue("USESPHERICALFROMREFLECTIONMAP", true);
defines.setValue("USEIRRADIANCEMAP", false);
if (this.forceIrradianceInFragment || this._scene.getEngine().getCaps().maxVaryingVectors <= 8) {
defines.setValue("USESPHERICALINVERTEX", false);
}
else {
defines.setValue("USESPHERICALINVERTEX", true);
}
}
}
};
ReflectionBlock.prototype.bind = function (effect, nodeMaterial, mesh, subMesh) {
_super.prototype.bind.call(this, effect, nodeMaterial, mesh);
var reflectionTexture = this._getTexture();
if (!reflectionTexture || !subMesh) {
return;
}
if (reflectionTexture.isCube) {
effect.setTexture(this._cubeSamplerName, reflectionTexture);
}
else {
effect.setTexture(this._2DSamplerName, reflectionTexture);
}
var width = reflectionTexture.getSize().width;
effect.setFloat3(this._vReflectionMicrosurfaceInfosName, width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
effect.setFloat2(this._vReflectionFilteringInfoName, width, _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_9__["Scalar"].Log2(width));
var defines = subMesh._materialDefines;
var polynomials = reflectionTexture.sphericalPolynomial;
if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
if (defines.SPHERICAL_HARMONICS) {
var preScaledHarmonics = polynomials.preScaledHarmonics;
effect.setVector3("vSphericalL00", preScaledHarmonics.l00);
effect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
effect.setVector3("vSphericalL10", preScaledHarmonics.l10);
effect.setVector3("vSphericalL11", preScaledHarmonics.l11);
effect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
effect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
effect.setVector3("vSphericalL20", preScaledHarmonics.l20);
effect.setVector3("vSphericalL21", preScaledHarmonics.l21);
effect.setVector3("vSphericalL22", preScaledHarmonics.l22);
}
else {
effect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
effect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
effect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
effect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
effect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
effect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
effect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
effect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
effect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
}
}
};
/**
* Gets the code to inject in the vertex shader
* @param state current state of the node material building
* @returns the shader code
*/
ReflectionBlock.prototype.handleVertexSide = function (state) {
var code = _super.prototype.handleVertexSide.call(this, state);
state._emitFunctionFromInclude("harmonicsFunctions", "//" + this.name, {
replaceStrings: [
{ search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" },
{ search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" },
]
});
var reflectionVectorName = state._getFreeVariableName("reflectionVector");
this._vEnvironmentIrradianceName = state._getFreeVariableName("vEnvironmentIrradiance");
state._emitVaryingFromString(this._vEnvironmentIrradianceName, "vec3", "defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)");
state._emitUniformFromString("vSphericalL00", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL1_1", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL10", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL11", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL2_2", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL2_1", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL20", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL21", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalL22", "vec3", "SPHERICAL_HARMONICS");
state._emitUniformFromString("vSphericalX", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalY", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalZ", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalXX_ZZ", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalYY_ZZ", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalZZ", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalXY", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalYZ", "vec3", "SPHERICAL_HARMONICS", true);
state._emitUniformFromString("vSphericalZX", "vec3", "SPHERICAL_HARMONICS", true);
code +=
"#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\n vec3 " + reflectionVectorName + " = vec3(" + this._reflectionMatrixName + " * vec4(normalize(" + this.worldNormal.associatedVariableName + ").xyz, 0)).xyz;\n #ifdef " + this._defineOppositeZ + "\n " + reflectionVectorName + ".z *= -1.0;\n #endif\n " + this._vEnvironmentIrradianceName + " = computeEnvironmentIrradiance(" + reflectionVectorName + ");\n #endif\r\n";
return code;
};
/**
* Gets the main code of the block (fragment side)
* @param state current state of the node material building
* @param normalVarName name of the existing variable corresponding to the normal
* @returns the shader code
*/
ReflectionBlock.prototype.getCode = function (state, normalVarName) {
var code = "";
this.handleFragmentSideInits(state);
state._emitFunctionFromInclude("harmonicsFunctions", "//" + this.name, {
replaceStrings: [
{ search: /uniform vec3 vSphericalL00;[\s\S]*?uniform vec3 vSphericalL22;/g, replace: "" },
{ search: /uniform vec3 vSphericalX;[\s\S]*?uniform vec3 vSphericalZX;/g, replace: "" },
]
});
state._emitFunction("sampleReflection", "\n #ifdef " + this._define3DName + "\n #define sampleReflection(s, c) textureCube(s, c)\n #else\n #define sampleReflection(s, c) texture2D(s, c)\n #endif\r\n", "//" + this.name);
state._emitFunction("sampleReflectionLod", "\n #ifdef " + this._define3DName + "\n #define sampleReflectionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleReflectionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\r\n", "//" + this.name);
var computeReflectionCoordsFunc = "\n vec3 computeReflectionCoordsPBR(vec4 worldPos, vec3 worldNormal) {\n " + this.handleFragmentSideCodeReflectionCoords('worldNormal', 'worldPos', true) + "\n return " + this._reflectionVectorName + ";\n }\r\n";
state._emitFunction("computeReflectionCoordsPBR", computeReflectionCoordsFunc, "//" + this.name);
this._vReflectionMicrosurfaceInfosName = state._getFreeVariableName("vReflectionMicrosurfaceInfos");
state._emitUniformFromString(this._vReflectionMicrosurfaceInfosName, "vec3");
this._vReflectionInfosName = state._getFreeVariableName("vReflectionInfos");
this._vReflectionFilteringInfoName = state._getFreeVariableName("vReflectionFilteringInfo");
state._emitUniformFromString(this._vReflectionFilteringInfoName, "vec2");
code += "#ifdef REFLECTION\n vec2 " + this._vReflectionInfosName + " = vec2(1., 0.);\n\n reflectionOutParams reflectionOut;\n\n reflectionBlock(\n " + ("v_" + this.worldPosition.associatedVariableName + ".xyz") + ",\n " + normalVarName + ",\n alphaG,\n " + this._vReflectionMicrosurfaceInfosName + ",\n " + this._vReflectionInfosName + ",\n " + this.reflectionColor + ",\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #if defined(" + this._defineLODReflectionAlpha + ") && !defined(" + this._defineSkyboxName + ")\n NdotVUnclamped,\n #endif\n #ifdef " + this._defineLinearSpecularReflection + "\n roughness,\n #endif\n #ifdef " + this._define3DName + "\n " + this._cubeSamplerName + ",\n #else\n " + this._2DSamplerName + ",\n #endif\n #if defined(NORMAL) && defined(USESPHERICALINVERTEX)\n " + this._vEnvironmentIrradianceName + ",\n #endif\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n " + this._reflectionMatrixName + ",\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler, // ** not handled **\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef " + this._define3DName + "\n " + this._cubeSamplerName + ",\n " + this._cubeSamplerName + ",\n #else\n " + this._2DSamplerName + ",\n " + this._2DSamplerName + ",\n #endif\n #endif\n reflectionOut\n );\n #endif\r\n";
return code;
};
ReflectionBlock.prototype._buildBlock = function (state) {
this._scene = state.sharedData.scene;
if (state.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) {
this._defineLODReflectionAlpha = state._getFreeDefineName("LODINREFLECTIONALPHA");
this._defineLinearSpecularReflection = state._getFreeDefineName("LINEARSPECULARREFLECTION");
}
return this;
};
ReflectionBlock.prototype._dumpPropertiesCode = function () {
var codeString = _super.prototype._dumpPropertiesCode.call(this);
codeString += this._codeVariableName + ".useSphericalHarmonics = " + this.useSphericalHarmonics + ";\r\n";
codeString += this._codeVariableName + ".forceIrradianceInFragment = " + this.forceIrradianceInFragment + ";\r\n";
return codeString;
};
ReflectionBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.useSphericalHarmonics = this.useSphericalHarmonics;
serializationObject.forceIrradianceInFragment = this.forceIrradianceInFragment;
return serializationObject;
};
ReflectionBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.useSphericalHarmonics = serializationObject.useSphericalHarmonics;
this.forceIrradianceInFragment = serializationObject.forceIrradianceInFragment;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_8__["editableInPropertyPage"])("Spherical Harmonics", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_8__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], ReflectionBlock.prototype, "useSphericalHarmonics", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_8__["editableInPropertyPage"])("Force irradiance in fragment", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_8__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], ReflectionBlock.prototype, "forceIrradianceInFragment", void 0);
return ReflectionBlock;
}(_Dual_reflectionTextureBaseBlock__WEBPACK_IMPORTED_MODULE_6__["ReflectionTextureBaseBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ReflectionBlock"] = ReflectionBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/reflectivityBlock.ts":
/*!********************************************************!*\
!*** ./Materials/Node/Blocks/PBR/reflectivityBlock.ts ***!
\********************************************************/
/*! exports provided: ReflectivityBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectivityBlock", function() { return ReflectivityBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Maths/math.color */ "./Maths/math.color.ts");
/**
* Block used to implement the reflectivity module of the PBR material
*/
var ReflectivityBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReflectivityBlock, _super);
/**
* Create a new ReflectivityBlock
* @param name defines the block name
*/
function ReflectivityBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment) || this;
_this._metallicReflectanceColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_8__["Color3"].White();
_this._metallicF0Factor = 1;
/**
* Specifies if the metallic texture contains the ambient occlusion information in its red channel.
*/
_this.useAmbientOcclusionFromMetallicTextureRed = false;
/**
* Specifies if the metallic texture contains the metallness information in its blue channel.
*/
_this.useMetallnessFromMetallicTextureBlue = true;
/**
* Specifies if the metallic texture contains the roughness information in its alpha channel.
*/
_this.useRoughnessFromMetallicTextureAlpha = false;
/**
* Specifies if the metallic texture contains the roughness information in its green channel.
*/
_this.useRoughnessFromMetallicTextureGreen = true;
_this._isUnique = true;
_this.registerInput("metallic", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("roughness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("texture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockConnectionPointTypes"].Color4, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("reflectivity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialConnectionPointCustomObject"]("reflectivity", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_7__["NodeMaterialConnectionPointDirection"].Output, ReflectivityBlock, "ReflectivityBlock"));
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
ReflectivityBlock.prototype.initialize = function (state) {
state._excludeVariableName("baseColor");
state._excludeVariableName("reflectivityOut");
state._excludeVariableName("microSurface");
state._excludeVariableName("roughness");
};
/**
* Gets the current class name
* @returns the class name
*/
ReflectivityBlock.prototype.getClassName = function () {
return "ReflectivityBlock";
};
Object.defineProperty(ReflectivityBlock.prototype, "metallic", {
/**
* Gets the metallic input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectivityBlock.prototype, "roughness", {
/**
* Gets the roughness input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectivityBlock.prototype, "texture", {
/**
* Gets the texture input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectivityBlock.prototype, "reflectivity", {
/**
* Gets the reflectivity object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ReflectivityBlock.prototype.bind = function (effect, nodeMaterial, mesh, subMesh) {
var _a, _b, _c;
_super.prototype.bind.call(this, effect, nodeMaterial, mesh);
var outside_ior = 1; // consider air as clear coat and other layers would remap in the shader.
var ior = (_c = (_b = (_a = this.indexOfRefractionConnectionPoint) === null || _a === void 0 ? void 0 : _a.connectInputBlock) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : 1.5;
// We are here deriving our default reflectance from a common value for none metallic surface.
// Based of the schlick fresnel approximation model
// for dielectrics.
var f0 = Math.pow((ior - outside_ior) / (ior + outside_ior), 2);
// Tweak the default F0 and F90 based on our given setup
this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, _Maths_math_color__WEBPACK_IMPORTED_MODULE_8__["TmpColors"].Color3[0]);
var metallicF90 = this._metallicF0Factor;
effect.setColor4(this._vMetallicReflectanceFactorsName, _Maths_math_color__WEBPACK_IMPORTED_MODULE_8__["TmpColors"].Color3[0], metallicF90);
};
/**
* Gets the main code of the block (fragment side)
* @param state current state of the node material building
* @param aoIntensityVarName name of the variable with the ambient occlusion intensity
* @returns the shader code
*/
ReflectivityBlock.prototype.getCode = function (state, aoIntensityVarName) {
var _a;
var metalRoughTexture = this.texture.isConnected ? (_a = this.texture.connectedPoint) === null || _a === void 0 ? void 0 : _a.associatedVariableName : null;
this._vMetallicReflectanceFactorsName = state._getFreeVariableName("vMetallicReflectanceFactors");
state._emitUniformFromString(this._vMetallicReflectanceFactorsName, "vec4");
// note: metallic F0 factor = 1
var code = "vec3 baseColor = surfaceAlbedo;\n reflectivityOutParams reflectivityOut;\n\n reflectivityBlock(\n vec4(" + this.metallic.associatedVariableName + ", " + this.roughness.associatedVariableName + ", 0., 0.),\n #ifdef METALLICWORKFLOW\n surfaceAlbedo,\n " + this._vMetallicReflectanceFactorsName + ",\n #endif\n #ifdef REFLECTIVITY\n vec3(0., 0., " + aoIntensityVarName + "),\n " + metalRoughTexture + ",\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor,\n #endif\n #ifdef MICROSURFACEMAP\n microSurfaceTexel, <== not handled!\n #endif\n reflectivityOut\n );\n\n float microSurface = reflectivityOut.microSurface;\n float roughness = reflectivityOut.roughness;\n\n #ifdef METALLICWORKFLOW\n surfaceAlbedo = reflectivityOut.surfaceAlbedo;\n #endif\n #if defined(METALLICWORKFLOW) && defined(REFLECTIVITY) && defined(AOSTOREINMETALMAPRED)\n aoOut.ambientOcclusionColor = reflectivityOut.ambientOcclusionColor;\n #endif\r\n";
return code;
};
ReflectivityBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
defines.setValue("REFLECTIVITY", this.texture.isConnected, true);
defines.setValue("AOSTOREINMETALMAPRED", this.useAmbientOcclusionFromMetallicTextureRed, true);
defines.setValue("METALLNESSSTOREINMETALMAPBLUE", this.useMetallnessFromMetallicTextureBlue, true);
defines.setValue("ROUGHNESSSTOREINMETALMAPALPHA", this.useRoughnessFromMetallicTextureAlpha, true);
defines.setValue("ROUGHNESSSTOREINMETALMAPGREEN", !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen, true);
};
ReflectivityBlock.prototype._buildBlock = function (state) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.blocksWithDefines.push(this);
state.sharedData.bindableBlocks.push(this);
}
return this;
};
ReflectivityBlock.prototype._dumpPropertiesCode = function () {
var codeString = "";
codeString += this._codeVariableName + ".useAmbientOcclusionFromMetallicTextureRed = " + this.useAmbientOcclusionFromMetallicTextureRed + ";\r\n";
codeString += this._codeVariableName + ".useMetallnessFromMetallicTextureBlue = " + this.useMetallnessFromMetallicTextureBlue + ";\r\n";
codeString += this._codeVariableName + ".useRoughnessFromMetallicTextureAlpha = " + this.useRoughnessFromMetallicTextureAlpha + ";\r\n";
codeString += this._codeVariableName + ".useRoughnessFromMetallicTextureGreen = " + this.useRoughnessFromMetallicTextureGreen + ";\r\n";
return codeString;
};
ReflectivityBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.useAmbientOcclusionFromMetallicTextureRed = this.useAmbientOcclusionFromMetallicTextureRed;
serializationObject.useMetallnessFromMetallicTextureBlue = this.useMetallnessFromMetallicTextureBlue;
serializationObject.useRoughnessFromMetallicTextureAlpha = this.useRoughnessFromMetallicTextureAlpha;
serializationObject.useRoughnessFromMetallicTextureGreen = this.useRoughnessFromMetallicTextureGreen;
return serializationObject;
};
ReflectivityBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.useAmbientOcclusionFromMetallicTextureRed = serializationObject.useAmbientOcclusionFromMetallicTextureRed;
this.useMetallnessFromMetallicTextureBlue = serializationObject.useMetallnessFromMetallicTextureBlue;
this.useRoughnessFromMetallicTextureAlpha = serializationObject.useRoughnessFromMetallicTextureAlpha;
this.useRoughnessFromMetallicTextureGreen = serializationObject.useRoughnessFromMetallicTextureGreen;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["editableInPropertyPage"])("AO from red channel", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["PropertyTypeForEdition"].Boolean, "METALLIC WORKFLOW", { "notifiers": { "update": true } })
], ReflectivityBlock.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["editableInPropertyPage"])("Metallness from blue channel", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["PropertyTypeForEdition"].Boolean, "METALLIC WORKFLOW", { "notifiers": { "update": true } })
], ReflectivityBlock.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["editableInPropertyPage"])("Roughness from alpha channel", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["PropertyTypeForEdition"].Boolean, "METALLIC WORKFLOW", { "notifiers": { "update": true } })
], ReflectivityBlock.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["editableInPropertyPage"])("Roughness from green channel", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_3__["PropertyTypeForEdition"].Boolean, "METALLIC WORKFLOW", { "notifiers": { "update": true } })
], ReflectivityBlock.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
return ReflectivityBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_2__["_TypeStore"].RegisteredTypes["BABYLON.ReflectivityBlock"] = ReflectivityBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/refractionBlock.ts":
/*!******************************************************!*\
!*** ./Materials/Node/Blocks/PBR/refractionBlock.ts ***!
\******************************************************/
/*! exports provided: RefractionBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefractionBlock", function() { return RefractionBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../Textures/cubeTexture */ "./Materials/Textures/cubeTexture.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../../Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/**
* Block used to implement the refraction part of the sub surface module of the PBR material
*/
var RefractionBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RefractionBlock, _super);
/**
* Create a new RefractionBlock
* @param name defines the block name
*/
function RefractionBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
/**
* This parameters will make the material used its opacity to control how much it is refracting aginst not.
* Materials half opaque for instance using refraction could benefit from this control.
*/
_this.linkRefractionWithTransparency = false;
/**
* Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
*/
_this.invertRefractionY = false;
_this._isUnique = true;
_this.registerInput("intensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("indexOfRefraction", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("tintAtDistance", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("view", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Matrix, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("refraction", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialConnectionPointCustomObject"]("refraction", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialConnectionPointDirection"].Output, RefractionBlock, "RefractionBlock"));
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
RefractionBlock.prototype.getClassName = function () {
return "RefractionBlock";
};
Object.defineProperty(RefractionBlock.prototype, "intensity", {
/**
* Gets the intensity input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractionBlock.prototype, "indexOfRefraction", {
/**
* Gets the index of refraction input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractionBlock.prototype, "tintAtDistance", {
/**
* Gets the tint at distance input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractionBlock.prototype, "view", {
/**
* Gets the view input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractionBlock.prototype, "refraction", {
/**
* Gets the refraction object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractionBlock.prototype, "hasTexture", {
/**
* Returns true if the block has a texture
*/
get: function () {
return !!this._getTexture();
},
enumerable: false,
configurable: true
});
RefractionBlock.prototype._getTexture = function () {
if (this.texture) {
return this.texture;
}
return this._scene.environmentTexture;
};
RefractionBlock.prototype.autoConfigure = function (material) {
if (!this.intensity.isConnected) {
var intensityInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("Refraction intensity", _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment, _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"].Float);
intensityInput.value = 1;
intensityInput.output.connectTo(this.intensity);
}
if (!this.view.isConnected) {
var viewInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialSystemValues"].View; });
if (!viewInput) {
viewInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("view");
viewInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_11__["NodeMaterialSystemValues"].View);
}
viewInput.output.connectTo(this.view);
}
};
RefractionBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
var refractionTexture = this._getTexture();
var refraction = refractionTexture && refractionTexture.getTextureMatrix;
defines.setValue("SS_REFRACTION", refraction, true);
if (!refraction) {
return;
}
defines.setValue(this._define3DName, refractionTexture.isCube, true);
defines.setValue(this._defineLODRefractionAlpha, refractionTexture.lodLevelInAlpha, true);
defines.setValue(this._defineLinearSpecularRefraction, refractionTexture.linearSpecularLOD, true);
defines.setValue(this._defineOppositeZ, this._scene.useRightHandedSystem ? !refractionTexture.invertZ : refractionTexture.invertZ, true);
defines.setValue("SS_LINKREFRACTIONTOTRANSPARENCY", this.linkRefractionWithTransparency, true);
defines.setValue("SS_GAMMAREFRACTION", refractionTexture.gammaSpace, true);
defines.setValue("SS_RGBDREFRACTION", refractionTexture.isRGBD, true);
};
RefractionBlock.prototype.isReady = function () {
var texture = this._getTexture();
if (texture && !texture.isReadyOrNotBlocking()) {
return false;
}
return true;
};
RefractionBlock.prototype.bind = function (effect, nodeMaterial, mesh, subMesh) {
var _a, _b;
_super.prototype.bind.call(this, effect, nodeMaterial, mesh);
var refractionTexture = this._getTexture();
if (!refractionTexture) {
return;
}
if (refractionTexture.isCube) {
effect.setTexture(this._cubeSamplerName, refractionTexture);
}
else {
effect.setTexture(this._2DSamplerName, refractionTexture);
}
effect.setMatrix(this._refractionMatrixName, refractionTexture.getReflectionTextureMatrix());
var depth = 1.0;
if (!refractionTexture.isCube) {
if (refractionTexture.depth) {
depth = refractionTexture.depth;
}
}
var indexOfRefraction = (_b = (_a = this.indexOfRefraction.connectInputBlock) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 1.5;
effect.setFloat4(this._vRefractionInfosName, refractionTexture.level, 1 / indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
effect.setFloat3(this._vRefractionMicrosurfaceInfosName, refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
};
/**
* Gets the main code of the block (fragment side)
* @param state current state of the node material building
* @returns the shader code
*/
RefractionBlock.prototype.getCode = function (state) {
var code = "";
state.sharedData.blockingBlocks.push(this);
state.sharedData.textureBlocks.push(this);
// Samplers
this._cubeSamplerName = state._getFreeVariableName(this.name + "CubeSampler");
state.samplers.push(this._cubeSamplerName);
this._2DSamplerName = state._getFreeVariableName(this.name + "2DSampler");
state.samplers.push(this._2DSamplerName);
this._define3DName = state._getFreeDefineName("SS_REFRACTIONMAP_3D");
state._samplerDeclaration += "#ifdef " + this._define3DName + "\r\n";
state._samplerDeclaration += "uniform samplerCube " + this._cubeSamplerName + ";\r\n";
state._samplerDeclaration += "#else\r\n";
state._samplerDeclaration += "uniform sampler2D " + this._2DSamplerName + ";\r\n";
state._samplerDeclaration += "#endif\r\n";
// Fragment
state.sharedData.blocksWithDefines.push(this);
state.sharedData.bindableBlocks.push(this);
this._defineLODRefractionAlpha = state._getFreeDefineName("SS_LODINREFRACTIONALPHA");
this._defineLinearSpecularRefraction = state._getFreeDefineName("SS_LINEARSPECULARREFRACTION");
this._defineOppositeZ = state._getFreeDefineName("SS_REFRACTIONMAP_OPPOSITEZ");
this._refractionMatrixName = state._getFreeVariableName("refractionMatrix");
state._emitUniformFromString(this._refractionMatrixName, "mat4");
state._emitFunction("sampleRefraction", "\n #ifdef " + this._define3DName + "\n #define sampleRefraction(s, c) textureCube(s, c)\n #else\n #define sampleRefraction(s, c) texture2D(s, c)\n #endif\r\n", "//" + this.name);
state._emitFunction("sampleRefractionLod", "\n #ifdef " + this._define3DName + "\n #define sampleRefractionLod(s, c, l) textureCubeLodEXT(s, c, l)\n #else\n #define sampleRefractionLod(s, c, l) texture2DLodEXT(s, c, l)\n #endif\r\n", "//" + this.name);
this._vRefractionMicrosurfaceInfosName = state._getFreeVariableName("vRefractionMicrosurfaceInfos");
state._emitUniformFromString(this._vRefractionMicrosurfaceInfosName, "vec3");
this._vRefractionInfosName = state._getFreeVariableName("vRefractionInfos");
state._emitUniformFromString(this._vRefractionInfosName, "vec4");
return code;
};
RefractionBlock.prototype._buildBlock = function (state) {
this._scene = state.sharedData.scene;
return this;
};
RefractionBlock.prototype._dumpPropertiesCode = function () {
var codeString = _super.prototype._dumpPropertiesCode.call(this);
if (this.texture) {
if (this.texture.isCube) {
codeString = this._codeVariableName + ".texture = new BABYLON.CubeTexture(\"" + this.texture.name + "\");\r\n";
}
else {
codeString = this._codeVariableName + ".texture = new BABYLON.Texture(\"" + this.texture.name + "\");\r\n";
}
codeString += this._codeVariableName + ".texture.coordinatesMode = " + this.texture.coordinatesMode + ";\r\n";
}
codeString += this._codeVariableName + ".linkRefractionWithTransparency = " + this.linkRefractionWithTransparency + ";\r\n";
codeString += this._codeVariableName + ".invertRefractionY = " + this.invertRefractionY + ";\r\n";
return codeString;
};
RefractionBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
if (this.texture) {
serializationObject.texture = this.texture.serialize();
}
serializationObject.linkRefractionWithTransparency = this.linkRefractionWithTransparency;
serializationObject.invertRefractionY = this.invertRefractionY;
return serializationObject;
};
RefractionBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
if (serializationObject.texture) {
rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
if (serializationObject.texture.isCube) {
this.texture = _Textures_cubeTexture__WEBPACK_IMPORTED_MODULE_9__["CubeTexture"].Parse(serializationObject.texture, scene, rootUrl);
}
else {
this.texture = _Textures_texture__WEBPACK_IMPORTED_MODULE_10__["Texture"].Parse(serializationObject.texture, scene, rootUrl);
}
}
this.linkRefractionWithTransparency = serializationObject.linkRefractionWithTransparency;
this.invertRefractionY = serializationObject.invertRefractionY;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_7__["editableInPropertyPage"])("Link refraction to transparency", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_7__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], RefractionBlock.prototype, "linkRefractionWithTransparency", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_7__["editableInPropertyPage"])("Invert refraction Y", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_7__["PropertyTypeForEdition"].Boolean, "ADVANCED", { "notifiers": { "update": true } })
], RefractionBlock.prototype, "invertRefractionY", void 0);
return RefractionBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.RefractionBlock"] = RefractionBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/sheenBlock.ts":
/*!*************************************************!*\
!*** ./Materials/Node/Blocks/PBR/sheenBlock.ts ***!
\*************************************************/
/*! exports provided: SheenBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SheenBlock", function() { return SheenBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/**
* Block used to implement the sheen module of the PBR material
*/
var SheenBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SheenBlock, _super);
/**
* Create a new SheenBlock
* @param name defines the block name
*/
function SheenBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) || this;
/**
* If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.
* It allows the strength of the sheen effect to not depend on the base color of the material,
* making it easier to setup and tweak the effect
*/
_this.albedoScaling = false;
/**
* Defines if the sheen is linked to the sheen color.
*/
_this.linkSheenWithAlbedo = false;
_this._isUnique = true;
_this.registerInput("intensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("roughness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("sheen", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_7__["NodeMaterialConnectionPointCustomObject"]("sheen", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Output, SheenBlock, "SheenBlock"));
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
SheenBlock.prototype.initialize = function (state) {
state._excludeVariableName("sheenOut");
state._excludeVariableName("sheenMapData");
state._excludeVariableName("vSheenColor");
state._excludeVariableName("vSheenRoughness");
};
/**
* Gets the current class name
* @returns the class name
*/
SheenBlock.prototype.getClassName = function () {
return "SheenBlock";
};
Object.defineProperty(SheenBlock.prototype, "intensity", {
/**
* Gets the intensity input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SheenBlock.prototype, "color", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SheenBlock.prototype, "roughness", {
/**
* Gets the roughness input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SheenBlock.prototype, "sheen", {
/**
* Gets the sheen object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
SheenBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
defines.setValue("SHEEN", true);
defines.setValue("SHEEN_LINKWITHALBEDO", this.linkSheenWithAlbedo, true);
defines.setValue("SHEEN_ROUGHNESS", this.roughness.isConnected, true);
defines.setValue("SHEEN_ALBEDOSCALING", this.albedoScaling, true);
};
/**
* Gets the main code of the block (fragment side)
* @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module
* @returns the shader code
*/
SheenBlock.prototype.getCode = function (reflectionBlock) {
var code = "";
var color = this.color.isConnected ? this.color.associatedVariableName : "vec3(1.)";
var intensity = this.intensity.isConnected ? this.intensity.associatedVariableName : "1.";
var roughness = this.roughness.isConnected ? this.roughness.associatedVariableName : "0.";
var texture = "vec4(0.)";
code = "#ifdef SHEEN\n sheenOutParams sheenOut;\n\n vec4 vSheenColor = vec4(" + color + ", " + intensity + ");\n\n sheenBlock(\n vSheenColor,\n #ifdef SHEEN_ROUGHNESS\n " + roughness + ",\n #endif\n roughness,\n #ifdef SHEEN_TEXTURE\n " + texture + ",\n #endif\n reflectance,\n #ifdef SHEEN_LINKWITHALBEDO\n baseColor,\n surfaceAlbedo,\n #endif\n #ifdef ENVIRONMENTBRDF\n NdotV,\n environmentBrdf,\n #endif\n #if defined(REFLECTION) && defined(ENVIRONMENTBRDF)\n AARoughnessFactors,\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionMicrosurfaceInfosName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._vReflectionInfosName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock.reflectionColor) + ",\n vLightingIntensity,\n #ifdef " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) + "\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName) + ",\n #else\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName) + ",\n #endif\n reflectionOut.reflectionCoords,\n NdotVUnclamped,\n #ifndef LODBASEDMICROSFURACE\n #ifdef " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) + "\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._cubeSamplerName) + ",\n #else\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName) + ",\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._2DSamplerName) + ",\n #endif\n #endif\n #if !defined(" + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) + ") && defined(RADIANCEOCCLUSION)\n seo,\n #endif\n #if !defined(" + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._defineSkyboxName) + ") && defined(HORIZONOCCLUSION) && defined(BUMP) && defined(" + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._define3DName) + ")\n eho,\n #endif\n #endif\n sheenOut\n );\n\n #ifdef SHEEN_LINKWITHALBEDO\n surfaceAlbedo = sheenOut.surfaceAlbedo;\n #endif\n #endif\r\n";
return code;
};
SheenBlock.prototype._buildBlock = function (state) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.blocksWithDefines.push(this);
}
return this;
};
SheenBlock.prototype._dumpPropertiesCode = function () {
var codeString = _super.prototype._dumpPropertiesCode.call(this);
codeString += this._codeVariableName + ".albedoScaling = " + this.albedoScaling + ";\r\n";
codeString += this._codeVariableName + ".linkSheenWithAlbedo = " + this.linkSheenWithAlbedo + ";\r\n";
return codeString;
};
SheenBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.albedoScaling = this.albedoScaling;
serializationObject.linkSheenWithAlbedo = this.linkSheenWithAlbedo;
return serializationObject;
};
SheenBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.albedoScaling = serializationObject.albedoScaling;
this.linkSheenWithAlbedo = serializationObject.linkSheenWithAlbedo;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("Albedo scaling", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Boolean, "PROPERTIES", { "notifiers": { "update": true } })
], SheenBlock.prototype, "albedoScaling", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("Link sheen with albedo", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Boolean, "PROPERTIES", { "notifiers": { "update": true } })
], SheenBlock.prototype, "linkSheenWithAlbedo", void 0);
return SheenBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SheenBlock"] = SheenBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/PBR/subSurfaceBlock.ts":
/*!******************************************************!*\
!*** ./Materials/Node/Blocks/PBR/subSurfaceBlock.ts ***!
\******************************************************/
/*! exports provided: SubSurfaceBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubSurfaceBlock", function() { return SubSurfaceBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../nodeMaterialConnectionPointCustomObject */ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts");
/* harmony import */ var _refractionBlock__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./refractionBlock */ "./Materials/Node/Blocks/PBR/refractionBlock.ts");
/**
* Block used to implement the sub surface module of the PBR material
*/
var SubSurfaceBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SubSurfaceBlock, _super);
/**
* Create a new SubSurfaceBlock
* @param name defines the block name
*/
function SubSurfaceBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) || this;
/**
* Stores the intensity of the different subsurface effects in the thickness texture.
* * the green channel is the translucency intensity.
* * the blue channel is the scattering intensity.
* * the alpha channel is the refraction intensity.
*/
_this.useMaskFromThicknessTexture = false;
_this._isUnique = true;
_this.registerInput("minThickness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("maxThickness", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("thicknessTexture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("tintColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("translucencyIntensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("translucencyDiffusionDistance", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("refraction", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, true, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialConnectionPointCustomObject"]("refraction", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Input, _refractionBlock__WEBPACK_IMPORTED_MODULE_9__["RefractionBlock"], "RefractionBlock"));
_this.registerOutput("subsurface", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Object, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, new _nodeMaterialConnectionPointCustomObject__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialConnectionPointCustomObject"]("subsurface", _this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialConnectionPointDirection"].Output, SubSurfaceBlock, "SubSurfaceBlock"));
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
SubSurfaceBlock.prototype.initialize = function (state) {
state._excludeVariableName("subSurfaceOut");
state._excludeVariableName("vThicknessParam");
state._excludeVariableName("vTintColor");
state._excludeVariableName("vSubSurfaceIntensity");
};
/**
* Gets the current class name
* @returns the class name
*/
SubSurfaceBlock.prototype.getClassName = function () {
return "SubSurfaceBlock";
};
Object.defineProperty(SubSurfaceBlock.prototype, "minThickness", {
/**
* Gets the min thickness input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "maxThickness", {
/**
* Gets the max thickness input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "thicknessTexture", {
/**
* Gets the thickness texture component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "tintColor", {
/**
* Gets the tint color input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "translucencyIntensity", {
/**
* Gets the translucency intensity input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "translucencyDiffusionDistance", {
/**
* Gets the translucency diffusion distance input component
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "refraction", {
/**
* Gets the refraction object parameters
*/
get: function () {
return this._inputs[6];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubSurfaceBlock.prototype, "subsurface", {
/**
* Gets the sub surface object output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
SubSurfaceBlock.prototype.autoConfigure = function (material) {
if (!this.minThickness.isConnected) {
var minThicknessInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_7__["InputBlock"]("SubSurface min thickness", _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment, _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
minThicknessInput.value = 0;
minThicknessInput.output.connectTo(this.minThickness);
}
};
SubSurfaceBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
_super.prototype.prepareDefines.call(this, mesh, nodeMaterial, defines);
var translucencyEnabled = this.translucencyDiffusionDistance.isConnected || this.translucencyIntensity.isConnected;
defines.setValue("SUBSURFACE", translucencyEnabled || this.refraction.isConnected, true);
defines.setValue("SS_TRANSLUCENCY", translucencyEnabled, true);
defines.setValue("SS_THICKNESSANDMASK_TEXTURE", this.thicknessTexture.isConnected, true);
defines.setValue("SS_MASK_FROM_THICKNESS_TEXTURE", this.useMaskFromThicknessTexture, true);
};
/**
* Gets the main code of the block (fragment side)
* @param state current state of the node material building
* @param ssBlock instance of a SubSurfaceBlock or null if the code must be generated without an active sub surface module
* @param reflectionBlock instance of a ReflectionBlock null if the code must be generated without an active reflection module
* @param worldPosVarName name of the variable holding the world position
* @returns the shader code
*/
SubSurfaceBlock.GetCode = function (state, ssBlock, reflectionBlock, worldPosVarName) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
var code = "";
var minThickness = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.minThickness.isConnected) ? ssBlock.minThickness.associatedVariableName : "0.";
var maxThickness = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.maxThickness.isConnected) ? ssBlock.maxThickness.associatedVariableName : "1.";
var thicknessTexture = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.thicknessTexture.isConnected) ? ssBlock.thicknessTexture.associatedVariableName : "vec4(0.)";
var tintColor = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.tintColor.isConnected) ? ssBlock.tintColor.associatedVariableName : "vec3(1.)";
var translucencyIntensity = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyIntensity.associatedVariableName : "1.";
var translucencyDiffusionDistance = (ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDistance.isConnected) ? ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.translucencyDiffusionDistance.associatedVariableName : "vec3(1.)";
var refractionBlock = ((ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.refraction.isConnected) ? (_a = ssBlock === null || ssBlock === void 0 ? void 0 : ssBlock.refraction.connectedPoint) === null || _a === void 0 ? void 0 : _a.ownerBlock : null);
var refractionTintAtDistance = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.tintAtDistance.isConnected) ? refractionBlock.tintAtDistance.associatedVariableName : "1.";
var refractionIntensity = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.intensity.isConnected) ? refractionBlock.intensity.associatedVariableName : "1.";
var refractionView = (refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.view.isConnected) ? refractionBlock.view.associatedVariableName : "";
code += (_b = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock.getCode(state)) !== null && _b !== void 0 ? _b : "";
code += "subSurfaceOutParams subSurfaceOut;\n\n #ifdef SUBSURFACE\n vec2 vThicknessParam = vec2(" + minThickness + ", " + maxThickness + " - " + minThickness + ");\n vec4 vTintColor = vec4(" + tintColor + ", " + refractionTintAtDistance + ");\n vec3 vSubSurfaceIntensity = vec3(" + refractionIntensity + ", " + translucencyIntensity + ", 0.);\n\n subSurfaceBlock(\n vSubSurfaceIntensity,\n vThicknessParam,\n vTintColor,\n normalW,\n specularEnvironmentReflectance,\n #ifdef SS_THICKNESSANDMASK_TEXTURE\n " + thicknessTexture + ",\n #endif\n #ifdef REFLECTION\n #ifdef SS_TRANSLUCENCY\n " + (reflectionBlock === null || reflectionBlock === void 0 ? void 0 : reflectionBlock._reflectionMatrixName) + ",\n #ifdef USESPHERICALFROMREFLECTIONMAP\n #if !defined(NORMAL) || !defined(USESPHERICALINVERTEX)\n reflectionOut.irradianceVector,\n #endif\n #endif\n #ifdef USEIRRADIANCEMAP\n irradianceSampler,\n #endif\n #endif\n #endif\n #ifdef SS_REFRACTION\n " + worldPosVarName + ".xyz,\n viewDirectionW,\n " + refractionView + ",\n surfaceAlbedo,\n " + ((_c = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionInfosName) !== null && _c !== void 0 ? _c : "") + ",\n " + ((_d = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._refractionMatrixName) !== null && _d !== void 0 ? _d : "") + ",\n " + ((_e = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._vRefractionMicrosurfaceInfosName) !== null && _e !== void 0 ? _e : "") + ",\n vLightingIntensity,\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha,\n #endif\n #ifdef " + ((_f = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLODRefractionAlpha) !== null && _f !== void 0 ? _f : "IGNORE") + "\n NdotVUnclamped,\n #endif\n #ifdef " + ((_g = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._defineLinearSpecularRefraction) !== null && _g !== void 0 ? _g : "IGNORE") + "\n roughness,\n #else\n alphaG,\n #endif\n #ifdef " + ((_h = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _h !== void 0 ? _h : "IGNORE") + "\n " + ((_j = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _j !== void 0 ? _j : "") + ",\n #else\n " + ((_k = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _k !== void 0 ? _k : "") + ",\n #endif\n #ifndef LODBASEDMICROSFURACE\n #ifdef " + ((_l = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._define3DName) !== null && _l !== void 0 ? _l : "IGNORE") + "\n " + ((_m = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _m !== void 0 ? _m : "") + ",\n " + ((_o = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._cubeSamplerName) !== null && _o !== void 0 ? _o : "") + ",\n #else\n " + ((_p = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _p !== void 0 ? _p : "") + ",\n " + ((_q = refractionBlock === null || refractionBlock === void 0 ? void 0 : refractionBlock._2DSamplerName) !== null && _q !== void 0 ? _q : "") + ",\n #endif\n #endif\n #ifdef ANISOTROPIC\n anisotropicOut,\n #endif\n #endif\n #ifdef SS_TRANSLUCENCY\n " + translucencyDiffusionDistance + ",\n #endif\n subSurfaceOut\n );\n\n #ifdef SS_REFRACTION\n surfaceAlbedo = subSurfaceOut.surfaceAlbedo;\n #ifdef SS_LINKREFRACTIONTOTRANSPARENCY\n alpha = subSurfaceOut.alpha;\n #endif\n #endif\n #else\n subSurfaceOut.specularEnvironmentReflectance = specularEnvironmentReflectance;\n #endif\r\n";
return code;
};
SubSurfaceBlock.prototype._buildBlock = function (state) {
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Fragment) {
state.sharedData.blocksWithDefines.push(this);
}
return this;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("Mask from thickness texture", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Boolean, "PROPERTIES", { "notifiers": { "update": true } })
], SubSurfaceBlock.prototype, "useMaskFromThicknessTexture", void 0);
return SubSurfaceBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.SubSurfaceBlock"] = SubSurfaceBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Particle/index.ts":
/*!*************************************************!*\
!*** ./Materials/Node/Blocks/Particle/index.ts ***!
\*************************************************/
/*! exports provided: ParticleTextureBlock, ParticleRampGradientBlock, ParticleBlendMultiplyBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _particleTextureBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./particleTextureBlock */ "./Materials/Node/Blocks/Particle/particleTextureBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleTextureBlock", function() { return _particleTextureBlock__WEBPACK_IMPORTED_MODULE_0__["ParticleTextureBlock"]; });
/* harmony import */ var _particleRampGradientBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./particleRampGradientBlock */ "./Materials/Node/Blocks/Particle/particleRampGradientBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleRampGradientBlock", function() { return _particleRampGradientBlock__WEBPACK_IMPORTED_MODULE_1__["ParticleRampGradientBlock"]; });
/* harmony import */ var _particleBlendMultiplyBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./particleBlendMultiplyBlock */ "./Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleBlendMultiplyBlock", function() { return _particleBlendMultiplyBlock__WEBPACK_IMPORTED_MODULE_2__["ParticleBlendMultiplyBlock"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.ts":
/*!**********************************************************************!*\
!*** ./Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.ts ***!
\**********************************************************************/
/*! exports provided: ParticleBlendMultiplyBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleBlendMultiplyBlock", function() { return ParticleBlendMultiplyBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used for the particle blend multiply section
*/
var ParticleBlendMultiplyBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ParticleBlendMultiplyBlock, _super);
/**
* Create a new ParticleBlendMultiplyBlock
* @param name defines the block name
*/
function ParticleBlendMultiplyBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this._isUnique = true;
_this.registerInput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("alphaTexture", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerInput("alphaColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("blendColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ParticleBlendMultiplyBlock.prototype.getClassName = function () {
return "ParticleBlendMultiplyBlock";
};
Object.defineProperty(ParticleBlendMultiplyBlock.prototype, "color", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleBlendMultiplyBlock.prototype, "alphaTexture", {
/**
* Gets the alphaTexture input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleBlendMultiplyBlock.prototype, "alphaColor", {
/**
* Gets the alphaColor input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleBlendMultiplyBlock.prototype, "blendColor", {
/**
* Gets the blendColor output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
ParticleBlendMultiplyBlock.prototype.initialize = function (state) {
state._excludeVariableName("sourceAlpha");
};
ParticleBlendMultiplyBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
return;
}
state.compilationString += "\n #ifdef BLENDMULTIPLYMODE\n " + this._declareOutput(this.blendColor, state) + ";\n float sourceAlpha = " + this.alphaColor.associatedVariableName + " * " + this.alphaTexture.associatedVariableName + ";\n " + this.blendColor.associatedVariableName + ".rgb = " + this.color.associatedVariableName + ".rgb * sourceAlpha + vec3(1.0) * (1.0 - sourceAlpha);\n " + this.blendColor.associatedVariableName + ".a = " + this.color.associatedVariableName + ".a;\n #else\n " + this._declareOutput(this.blendColor, state) + " = " + this.color.associatedVariableName + ";\n #endif\n ";
return this;
};
return ParticleBlendMultiplyBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ParticleBlendMultiplyBlock"] = ParticleBlendMultiplyBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Particle/particleRampGradientBlock.ts":
/*!*********************************************************************!*\
!*** ./Materials/Node/Blocks/Particle/particleRampGradientBlock.ts ***!
\*********************************************************************/
/*! exports provided: ParticleRampGradientBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleRampGradientBlock", function() { return ParticleRampGradientBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used for the particle ramp gradient section
*/
var ParticleRampGradientBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ParticleRampGradientBlock, _super);
/**
* Create a new ParticleRampGradientBlock
* @param name defines the block name
*/
function ParticleRampGradientBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this._isUnique = true;
_this.registerInput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
_this.registerOutput("rampColor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ParticleRampGradientBlock.prototype.getClassName = function () {
return "ParticleRampGradientBlock";
};
Object.defineProperty(ParticleRampGradientBlock.prototype, "color", {
/**
* Gets the color input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleRampGradientBlock.prototype, "rampColor", {
/**
* Gets the rampColor output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
ParticleRampGradientBlock.prototype.initialize = function (state) {
state._excludeVariableName("remapRanges");
state._excludeVariableName("rampSampler");
state._excludeVariableName("baseColor");
state._excludeVariableName("alpha");
state._excludeVariableName("remappedColorIndex");
state._excludeVariableName("rampColor");
state._excludeVariableName("finalAlpha");
};
ParticleRampGradientBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
return;
}
state._emit2DSampler("rampSampler");
state._emitVaryingFromString("remapRanges", "vec4", "RAMPGRADIENT");
state.compilationString += "\n #ifdef RAMPGRADIENT\n vec4 baseColor = " + this.color.associatedVariableName + ";\n float alpha = " + this.color.associatedVariableName + ".a;\n\n float remappedColorIndex = clamp((alpha - remapRanges.x) / remapRanges.y, 0.0, 1.0);\n\n vec4 rampColor = texture2D(rampSampler, vec2(1.0 - remappedColorIndex, 0.));\n baseColor.rgb *= rampColor.rgb;\n\n // Remapped alpha\n float finalAlpha = baseColor.a;\n baseColor.a = clamp((alpha * rampColor.a - remapRanges.z) / remapRanges.w, 0.0, 1.0);\n\n " + this._declareOutput(this.rampColor, state) + " = baseColor;\n #else\n " + this._declareOutput(this.rampColor, state) + " = " + this.color.associatedVariableName + ";\n #endif\n ";
return this;
};
return ParticleRampGradientBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ParticleRampGradientBlock"] = ParticleRampGradientBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Particle/particleTextureBlock.ts":
/*!****************************************************************!*\
!*** ./Materials/Node/Blocks/Particle/particleTextureBlock.ts ***!
\****************************************************************/
/*! exports provided: ParticleTextureBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParticleTextureBlock", function() { return ParticleTextureBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../Textures/texture */ "./Materials/Textures/texture.ts");
/**
* Base block used for the particle texture
*/
var ParticleTextureBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ParticleTextureBlock, _super);
/**
* Create a new ParticleTextureBlock
* @param name defines the block name
*/
function ParticleTextureBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Fragment) || this;
_this._samplerName = "diffuseSampler";
/**
* Gets or sets a boolean indicating if content needs to be converted to gamma space
*/
_this.convertToGammaSpace = false;
/**
* Gets or sets a boolean indicating if content needs to be converted to linear space
*/
_this.convertToLinearSpace = false;
_this._isUnique = true;
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].VertexAndFragment);
_this.registerOutput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("r", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("g", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("b", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this.registerOutput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ParticleTextureBlock.prototype.getClassName = function () {
return "ParticleTextureBlock";
};
Object.defineProperty(ParticleTextureBlock.prototype, "uv", {
/**
* Gets the uv input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleTextureBlock.prototype, "rgba", {
/**
* Gets the rgba output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleTextureBlock.prototype, "rgb", {
/**
* Gets the rgb output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleTextureBlock.prototype, "r", {
/**
* Gets the r output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleTextureBlock.prototype, "g", {
/**
* Gets the g output component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleTextureBlock.prototype, "b", {
/**
* Gets the b output component
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ParticleTextureBlock.prototype, "a", {
/**
* Gets the a output component
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
ParticleTextureBlock.prototype.initialize = function (state) {
state._excludeVariableName("diffuseSampler");
};
ParticleTextureBlock.prototype.autoConfigure = function (material) {
if (!this.uv.isConnected) {
var uvInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "particle_uv"; });
if (!uvInput) {
uvInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_4__["InputBlock"]("uv");
uvInput.setAsAttribute("particle_uv");
}
uvInput.output.connectTo(this.uv);
}
};
ParticleTextureBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
defines.setValue(this._linearDefineName, this.convertToGammaSpace, true);
defines.setValue(this._gammaDefineName, this.convertToLinearSpace, true);
};
ParticleTextureBlock.prototype.isReady = function () {
if (this.texture && !this.texture.isReadyOrNotBlocking()) {
return false;
}
return true;
};
ParticleTextureBlock.prototype._writeOutput = function (state, output, swizzle) {
state.compilationString += this._declareOutput(output, state) + " = " + this._tempTextureRead + "." + swizzle + ";\r\n";
state.compilationString += "#ifdef " + this._linearDefineName + "\r\n";
state.compilationString += output.associatedVariableName + " = toGammaSpace(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += "#ifdef " + this._gammaDefineName + "\r\n";
state.compilationString += output.associatedVariableName + " = toLinearSpace(" + output.associatedVariableName + ");\r\n";
state.compilationString += "#endif\r\n";
};
ParticleTextureBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) {
return;
}
this._tempTextureRead = state._getFreeVariableName("tempTextureRead");
state._emit2DSampler(this._samplerName);
state.sharedData.blockingBlocks.push(this);
state.sharedData.textureBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
this._linearDefineName = state._getFreeDefineName("ISLINEAR");
this._gammaDefineName = state._getFreeDefineName("ISGAMMA");
var comments = "//" + this.name;
state._emitFunctionFromInclude("helperFunctions", comments);
state.compilationString += "vec4 " + this._tempTextureRead + " = texture2D(" + this._samplerName + ", " + this.uv.associatedVariableName + ");\r\n";
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.hasEndpoints) {
this._writeOutput(state, output, output.name);
}
}
return this;
};
ParticleTextureBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.convertToGammaSpace = this.convertToGammaSpace;
serializationObject.convertToLinearSpace = this.convertToLinearSpace;
if (this.texture) {
serializationObject.texture = this.texture.serialize();
}
return serializationObject;
};
ParticleTextureBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.convertToGammaSpace = serializationObject.convertToGammaSpace;
this.convertToLinearSpace = !!serializationObject.convertToLinearSpace;
if (serializationObject.texture) {
rootUrl = serializationObject.texture.url.indexOf("data:") === 0 ? "" : rootUrl;
this.texture = _Textures_texture__WEBPACK_IMPORTED_MODULE_6__["Texture"].Parse(serializationObject.texture, scene, rootUrl);
}
};
return ParticleTextureBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.ParticleTextureBlock"] = ParticleTextureBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Vertex/bonesBlock.ts":
/*!****************************************************!*\
!*** ./Materials/Node/Blocks/Vertex/bonesBlock.ts ***!
\****************************************************/
/*! exports provided: BonesBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return BonesBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Shaders_ShadersInclude_bonesDeclaration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/bonesDeclaration */ "./Shaders/ShadersInclude/bonesDeclaration.ts");
/* harmony import */ var _Shaders_ShadersInclude_bonesVertex__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/bonesVertex */ "./Shaders/ShadersInclude/bonesVertex.ts");
/**
* Block used to add support for vertex skinning (bones)
*/
var BonesBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BonesBlock, _super);
/**
* Creates a new BonesBlock
* @param name defines the block name
*/
function BonesBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialBlockTargets"].Vertex) || this;
_this.registerInput("matricesIndices", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("matricesWeights", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("matricesIndicesExtra", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true);
_this.registerInput("matricesWeightsExtra", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true);
_this.registerInput("world", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
BonesBlock.prototype.initialize = function (state) {
state._excludeVariableName("boneSampler");
state._excludeVariableName("boneTextureWidth");
state._excludeVariableName("mBones");
state._excludeVariableName("BonesPerMesh");
};
/**
* Gets the current class name
* @returns the class name
*/
BonesBlock.prototype.getClassName = function () {
return "BonesBlock";
};
Object.defineProperty(BonesBlock.prototype, "matricesIndices", {
/**
* Gets the matrix indices input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(BonesBlock.prototype, "matricesWeights", {
/**
* Gets the matrix weights input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(BonesBlock.prototype, "matricesIndicesExtra", {
/**
* Gets the extra matrix indices input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(BonesBlock.prototype, "matricesWeightsExtra", {
/**
* Gets the extra matrix weights input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(BonesBlock.prototype, "world", {
/**
* Gets the world input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(BonesBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
BonesBlock.prototype.autoConfigure = function (material) {
if (!this.matricesIndices.isConnected) {
var matricesIndicesInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "matricesIndices"; });
if (!matricesIndicesInput) {
matricesIndicesInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("matricesIndices");
matricesIndicesInput.setAsAttribute("matricesIndices");
}
matricesIndicesInput.output.connectTo(this.matricesIndices);
}
if (!this.matricesWeights.isConnected) {
var matricesWeightsInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "matricesWeights"; });
if (!matricesWeightsInput) {
matricesWeightsInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("matricesWeights");
matricesWeightsInput.setAsAttribute("matricesWeights");
}
matricesWeightsInput.output.connectTo(this.matricesWeights);
}
if (!this.world.isConnected) {
var worldInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"].World; });
if (!worldInput) {
worldInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("world");
worldInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"].World);
}
worldInput.output.connectTo(this.world);
}
};
BonesBlock.prototype.provideFallbacks = function (mesh, fallbacks) {
if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
fallbacks.addCPUSkinningFallback(0, mesh);
}
};
BonesBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindBonesParameters(mesh, effect);
};
BonesBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (!defines._areAttributesDirty) {
return;
}
_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareDefinesForBones(mesh, defines);
};
BonesBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
// Register for compilation fallbacks
state.sharedData.blocksWithFallbacks.push(this);
// Register for binding
state.sharedData.bindableBlocks.push(this);
// Register for defines
state.sharedData.blocksWithDefines.push(this);
// Register internal uniforms and samplers
state.uniforms.push("boneTextureWidth");
state.uniforms.push("mBones");
state.samplers.push("boneSampler");
// Emit code
var comments = "//" + this.name;
state._emitFunctionFromInclude("bonesDeclaration", comments, {
removeAttributes: true,
removeUniforms: false,
removeVaryings: true,
removeIfDef: false
});
var influenceVariablename = state._getFreeVariableName("influence");
state.compilationString += state._emitCodeFromInclude("bonesVertex", comments, {
replaceStrings: [
{
search: /finalWorld=finalWorld\*influence;/,
replace: ""
},
{
search: /influence/gm,
replace: influenceVariablename
}
]
});
var output = this._outputs[0];
var worldInput = this.world;
state.compilationString += "#if NUM_BONE_INFLUENCERS>0\r\n";
state.compilationString += this._declareOutput(output, state) + (" = " + worldInput.associatedVariableName + " * " + influenceVariablename + ";\r\n");
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(output, state) + (" = " + worldInput.associatedVariableName + ";\r\n");
state.compilationString += "#endif\r\n";
return this;
};
return BonesBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.BonesBlock"] = BonesBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Vertex/index.ts":
/*!***********************************************!*\
!*** ./Materials/Node/Blocks/Vertex/index.ts ***!
\***********************************************/
/*! exports provided: VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, LightInformationBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _vertexOutputBlock__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./vertexOutputBlock */ "./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _vertexOutputBlock__WEBPACK_IMPORTED_MODULE_0__["VertexOutputBlock"]; });
/* harmony import */ var _bonesBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./bonesBlock */ "./Materials/Node/Blocks/Vertex/bonesBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _bonesBlock__WEBPACK_IMPORTED_MODULE_1__["BonesBlock"]; });
/* harmony import */ var _instancesBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./instancesBlock */ "./Materials/Node/Blocks/Vertex/instancesBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _instancesBlock__WEBPACK_IMPORTED_MODULE_2__["InstancesBlock"]; });
/* harmony import */ var _morphTargetsBlock__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./morphTargetsBlock */ "./Materials/Node/Blocks/Vertex/morphTargetsBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _morphTargetsBlock__WEBPACK_IMPORTED_MODULE_3__["MorphTargetsBlock"]; });
/* harmony import */ var _lightInformationBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./lightInformationBlock */ "./Materials/Node/Blocks/Vertex/lightInformationBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightInformationBlock", function() { return _lightInformationBlock__WEBPACK_IMPORTED_MODULE_4__["LightInformationBlock"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/Vertex/instancesBlock.ts":
/*!********************************************************!*\
!*** ./Materials/Node/Blocks/Vertex/instancesBlock.ts ***!
\********************************************************/
/*! exports provided: InstancesBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return InstancesBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to add support for instances
* @see https://doc.babylonjs.com/how_to/how_to_use_instances
*/
var InstancesBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InstancesBlock, _super);
/**
* Creates a new InstancesBlock
* @param name defines the block name
*/
function InstancesBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex) || this;
_this.registerInput("world0", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("world1", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("world2", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("world3", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("world", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Matrix, true);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this.registerOutput("instanceID", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
InstancesBlock.prototype.getClassName = function () {
return "InstancesBlock";
};
Object.defineProperty(InstancesBlock.prototype, "world0", {
/**
* Gets the first world row input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InstancesBlock.prototype, "world1", {
/**
* Gets the second world row input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InstancesBlock.prototype, "world2", {
/**
* Gets the third world row input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InstancesBlock.prototype, "world3", {
/**
* Gets the forth world row input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InstancesBlock.prototype, "world", {
/**
* Gets the world input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InstancesBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(InstancesBlock.prototype, "instanceID", {
/**
* Gets the isntanceID component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
InstancesBlock.prototype.autoConfigure = function (material) {
if (!this.world0.connectedPoint) {
var world0Input = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "world0"; });
if (!world0Input) {
world0Input = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("world0");
world0Input.setAsAttribute("world0");
}
world0Input.output.connectTo(this.world0);
}
if (!this.world1.connectedPoint) {
var world1Input = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "world1"; });
if (!world1Input) {
world1Input = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("world1");
world1Input.setAsAttribute("world1");
}
world1Input.output.connectTo(this.world1);
}
if (!this.world2.connectedPoint) {
var world2Input = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "world2"; });
if (!world2Input) {
world2Input = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("world2");
world2Input.setAsAttribute("world2");
}
world2Input.output.connectTo(this.world2);
}
if (!this.world3.connectedPoint) {
var world3Input = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "world3"; });
if (!world3Input) {
world3Input = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("world3");
world3Input.setAsAttribute("world3");
}
world3Input.output.connectTo(this.world3);
}
if (!this.world.connectedPoint) {
var worldInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "world"; });
if (!worldInput) {
worldInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("world");
worldInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialSystemValues"].World);
}
worldInput.output.connectTo(this.world);
}
this.world.define = "!INSTANCES || THIN_INSTANCES";
};
InstancesBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines, useInstances, subMesh) {
if (useInstances === void 0) { useInstances = false; }
var changed = false;
if (defines["INSTANCES"] !== useInstances) {
defines.setValue("INSTANCES", useInstances);
changed = true;
}
if (subMesh && defines["THIN_INSTANCES"] !== !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances)) {
defines.setValue("THIN_INSTANCES", !!(subMesh === null || subMesh === void 0 ? void 0 : subMesh.getRenderingMesh().hasThinInstances));
changed = true;
}
if (changed) {
defines.markAsUnprocessed();
}
};
InstancesBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
// Register for defines
state.sharedData.blocksWithDefines.push(this);
// Emit code
var output = this._outputs[0];
var instanceID = this._outputs[1];
var world0 = this.world0;
var world1 = this.world1;
var world2 = this.world2;
var world3 = this.world3;
state.compilationString += "#ifdef INSTANCES\r\n";
state.compilationString += this._declareOutput(output, state) + (" = mat4(" + world0.associatedVariableName + ", " + world1.associatedVariableName + ", " + world2.associatedVariableName + ", " + world3.associatedVariableName + ");\r\n");
state.compilationString += "#ifdef THIN_INSTANCES\r\n";
state.compilationString += output.associatedVariableName + " = " + this.world.associatedVariableName + " * " + output.associatedVariableName + ";\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += this._declareOutput(instanceID, state) + " = float(gl_InstanceID);\r\n";
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(output, state) + (" = " + this.world.associatedVariableName + ";\r\n");
state.compilationString += this._declareOutput(instanceID, state) + " = 0.0;\r\n";
state.compilationString += "#endif\r\n";
return this;
};
return InstancesBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_6__["_TypeStore"].RegisteredTypes["BABYLON.InstancesBlock"] = InstancesBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Vertex/lightInformationBlock.ts":
/*!***************************************************************!*\
!*** ./Materials/Node/Blocks/Vertex/lightInformationBlock.ts ***!
\***************************************************************/
/*! exports provided: LightInformationBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LightInformationBlock", function() { return LightInformationBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Lights_pointLight__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Lights/pointLight */ "./Lights/pointLight.ts");
/**
* Block used to get data information from a light
*/
var LightInformationBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LightInformationBlock, _super);
/**
* Creates a new LightInformationBlock
* @param name defines the block name
*/
function LightInformationBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this;
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, false, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex);
_this.registerOutput("direction", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this.registerOutput("intensity", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
LightInformationBlock.prototype.getClassName = function () {
return "LightInformationBlock";
};
Object.defineProperty(LightInformationBlock.prototype, "worldPosition", {
/**
* Gets the world position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightInformationBlock.prototype, "direction", {
/**
* Gets the direction output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightInformationBlock.prototype, "color", {
/**
* Gets the direction output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LightInformationBlock.prototype, "intensity", {
/**
* Gets the direction output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
LightInformationBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (!mesh) {
return;
}
if (this.light && this.light.isDisposed) {
this.light = null;
}
var light = this.light;
var scene = nodeMaterial.getScene();
if (!light && scene.lights.length) {
light = scene.lights[0];
}
if (!light || !light.isEnabled) {
effect.setFloat3(this._lightDataUniformName, 0, 0, 0);
effect.setFloat4(this._lightColorUniformName, 0, 0, 0, 0);
return;
}
light.transferToNodeMaterialEffect(effect, this._lightDataUniformName);
effect.setColor4(this._lightColorUniformName, light.diffuse, light.intensity);
};
LightInformationBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (!defines._areLightsDirty) {
return;
}
var light = this.light;
defines.setValue(this._lightTypeDefineName, light && light instanceof _Lights_pointLight__WEBPACK_IMPORTED_MODULE_5__["PointLight"] ? true : false);
};
LightInformationBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
state.sharedData.bindableBlocks.push(this);
state.sharedData.blocksWithDefines.push(this);
var direction = this.direction;
var color = this.color;
var intensity = this.intensity;
this._lightDataUniformName = state._getFreeVariableName("lightData");
this._lightColorUniformName = state._getFreeVariableName("lightColor");
this._lightTypeDefineName = state._getFreeDefineName("LIGHTPOINTTYPE");
state._emitUniformFromString(this._lightDataUniformName, "vec3");
state._emitUniformFromString(this._lightColorUniformName, "vec4");
state.compilationString += "#ifdef " + this._lightTypeDefineName + "\r\n";
state.compilationString += this._declareOutput(direction, state) + (" = normalize(" + this.worldPosition.associatedVariableName + ".xyz - " + this._lightDataUniformName + ");\r\n");
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(direction, state) + (" = " + this._lightDataUniformName + ";\r\n");
state.compilationString += "#endif\r\n";
state.compilationString += this._declareOutput(color, state) + (" = " + this._lightColorUniformName + ".rgb;\r\n");
state.compilationString += this._declareOutput(intensity, state) + (" = " + this._lightColorUniformName + ".a;\r\n");
return this;
};
LightInformationBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
if (this.light) {
serializationObject.lightId = this.light.id;
}
return serializationObject;
};
LightInformationBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
if (serializationObject.lightId) {
this.light = scene.getLightByID(serializationObject.lightId);
}
};
return LightInformationBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.LightInformationBlock"] = LightInformationBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Vertex/morphTargetsBlock.ts":
/*!***********************************************************!*\
!*** ./Materials/Node/Blocks/Vertex/morphTargetsBlock.ts ***!
\***********************************************************/
/*! exports provided: MorphTargetsBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return MorphTargetsBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Shaders_ShadersInclude_morphTargetsVertexDeclaration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/morphTargetsVertexDeclaration */ "./Shaders/ShadersInclude/morphTargetsVertexDeclaration.ts");
/* harmony import */ var _Shaders_ShadersInclude_morphTargetsVertexGlobalDeclaration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ../../../../Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration */ "./Shaders/ShadersInclude/morphTargetsVertexGlobalDeclaration.ts");
/**
* Block used to add morph targets support to vertex shader
*/
var MorphTargetsBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MorphTargetsBlock, _super);
/**
* Create a new MorphTargetsBlock
* @param name defines the block name
*/
function MorphTargetsBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this;
_this.registerInput("position", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("normal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("tangent", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("uv", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
_this.registerOutput("positionOutput", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("normalOutput", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("tangentOutput", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("uvOutput", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
MorphTargetsBlock.prototype.getClassName = function () {
return "MorphTargetsBlock";
};
Object.defineProperty(MorphTargetsBlock.prototype, "position", {
/**
* Gets the position input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "normal", {
/**
* Gets the normal input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "tangent", {
/**
* Gets the tangent input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "uv", {
/**
* Gets the tangent input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "positionOutput", {
/**
* Gets the position output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "normalOutput", {
/**
* Gets the normal output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "tangentOutput", {
/**
* Gets the tangent output component
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MorphTargetsBlock.prototype, "uvOutput", {
/**
* Gets the tangent output component
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
MorphTargetsBlock.prototype.initialize = function (state) {
state._excludeVariableName("morphTargetInfluences");
};
MorphTargetsBlock.prototype.autoConfigure = function (material) {
if (!this.position.isConnected) {
var positionInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "position"; });
if (!positionInput) {
positionInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("position");
positionInput.setAsAttribute();
}
positionInput.output.connectTo(this.position);
}
if (!this.normal.isConnected) {
var normalInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "normal"; });
if (!normalInput) {
normalInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("normal");
normalInput.setAsAttribute("normal");
}
normalInput.output.connectTo(this.normal);
}
if (!this.tangent.isConnected) {
var tangentInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "tangent"; });
if (!tangentInput) {
tangentInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("tangent");
tangentInput.setAsAttribute("tangent");
}
tangentInput.output.connectTo(this.tangent);
}
if (!this.uv.isConnected) {
var uvInput = material.getInputBlockByPredicate(function (b) { return b.isAttribute && b.name === "uv"; });
if (!uvInput) {
uvInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("uv");
uvInput.setAsAttribute("uv");
}
uvInput.output.connectTo(this.uv);
}
};
MorphTargetsBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines) {
if (!defines._areAttributesDirty) {
return;
}
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMorphTargets(mesh, defines);
};
MorphTargetsBlock.prototype.bind = function (effect, nodeMaterial, mesh) {
if (mesh && mesh.morphTargetManager && mesh.morphTargetManager.numInfluencers > 0) {
_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindMorphTargetParameters(mesh, effect);
}
};
MorphTargetsBlock.prototype.replaceRepeatableContent = function (vertexShaderState, fragmentShaderState, mesh, defines) {
var position = this.position;
var normal = this.normal;
var tangent = this.tangent;
var uv = this.uv;
var positionOutput = this.positionOutput;
var normalOutput = this.normalOutput;
var tangentOutput = this.tangentOutput;
var uvOutput = this.uvOutput;
var state = vertexShaderState;
var repeatCount = defines.NUM_MORPH_INFLUENCERS;
var manager = mesh.morphTargetManager;
var hasNormals = manager && manager.supportsNormals && defines["NORMAL"];
var hasTangents = manager && manager.supportsTangents && defines["TANGENT"];
var hasUVs = manager && manager.supportsUVs && defines["UV1"];
var injectionCode = "";
for (var index = 0; index < repeatCount; index++) {
injectionCode += "#ifdef MORPHTARGETS\r\n";
injectionCode += positionOutput.associatedVariableName + " += (position" + index + " - " + position.associatedVariableName + ") * morphTargetInfluences[" + index + "];\r\n";
if (hasNormals) {
injectionCode += "#ifdef MORPHTARGETS_NORMAL\r\n";
injectionCode += normalOutput.associatedVariableName + " += (normal" + index + " - " + normal.associatedVariableName + ") * morphTargetInfluences[" + index + "];\r\n";
injectionCode += "#endif\r\n";
}
if (hasTangents) {
injectionCode += "#ifdef MORPHTARGETS_TANGENT\r\n";
injectionCode += tangentOutput.associatedVariableName + ".xyz += (tangent" + index + " - " + tangent.associatedVariableName + ".xyz) * morphTargetInfluences[" + index + "];\r\n";
injectionCode += "#endif\r\n";
}
if (hasUVs) {
injectionCode += "#ifdef MORPHTARGETS_UV\r\n";
injectionCode += uvOutput.associatedVariableName + ".xy += (uv_" + index + " - " + uv.associatedVariableName + ".xy) * morphTargetInfluences[" + index + "];\r\n";
injectionCode += "#endif\r\n";
}
injectionCode += "#endif\r\n";
}
state.compilationString = state.compilationString.replace(this._repeatableContentAnchor, injectionCode);
if (repeatCount > 0) {
for (var index = 0; index < repeatCount; index++) {
state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].PositionKind + index);
if (hasNormals) {
state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].NormalKind + index);
}
if (hasTangents) {
state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].TangentKind + index);
}
if (hasUVs) {
state.attributes.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_5__["VertexBuffer"].UVKind + "_" + index);
}
}
}
};
MorphTargetsBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
// Register for defines
state.sharedData.blocksWithDefines.push(this);
// Register for binding
state.sharedData.bindableBlocks.push(this);
// Register for repeatable content generation
state.sharedData.repeatableContentBlocks.push(this);
// Emit code
var position = this.position;
var normal = this.normal;
var tangent = this.tangent;
var uv = this.uv;
var positionOutput = this.positionOutput;
var normalOutput = this.normalOutput;
var tangentOutput = this.tangentOutput;
var uvOutput = this.uvOutput;
var comments = "//" + this.name;
state.uniforms.push("morphTargetInfluences");
state._emitFunctionFromInclude("morphTargetsVertexGlobalDeclaration", comments);
state._emitFunctionFromInclude("morphTargetsVertexDeclaration", comments, {
repeatKey: "maxSimultaneousMorphTargets"
});
state.compilationString += this._declareOutput(positionOutput, state) + " = " + position.associatedVariableName + ";\r\n";
state.compilationString += "#ifdef NORMAL\r\n";
state.compilationString += this._declareOutput(normalOutput, state) + " = " + normal.associatedVariableName + ";\r\n";
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(normalOutput, state) + " = vec3(0., 0., 0.);\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += "#ifdef TANGENT\r\n";
state.compilationString += this._declareOutput(tangentOutput, state) + " = " + tangent.associatedVariableName + ";\r\n";
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(tangentOutput, state) + " = vec3(0., 0., 0.);\r\n";
state.compilationString += "#endif\r\n";
state.compilationString += "#ifdef UV1\r\n";
state.compilationString += this._declareOutput(uvOutput, state) + " = " + uv.associatedVariableName + ";\r\n";
state.compilationString += "#else\r\n";
state.compilationString += this._declareOutput(uvOutput, state) + " = vec2(0., 0.);\r\n";
state.compilationString += "#endif\r\n";
// Repeatable content
this._repeatableContentAnchor = state._repeatableContentAnchor;
state.compilationString += this._repeatableContentAnchor;
return this;
};
return MorphTargetsBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_7__["_TypeStore"].RegisteredTypes["BABYLON.MorphTargetsBlock"] = MorphTargetsBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts":
/*!***********************************************************!*\
!*** ./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts ***!
\***********************************************************/
/*! exports provided: VertexOutputBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return VertexOutputBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to output the vertex position
*/
var VertexOutputBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VertexOutputBlock, _super);
/**
* Creates a new VertexOutputBlock
* @param name defines the block name
*/
function VertexOutputBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex, true) || this;
_this.registerInput("vector", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
VertexOutputBlock.prototype.getClassName = function () {
return "VertexOutputBlock";
};
Object.defineProperty(VertexOutputBlock.prototype, "vector", {
/**
* Gets the vector input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
VertexOutputBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var input = this.vector;
state.compilationString += "gl_Position = " + input.associatedVariableName + ";\r\n";
return this;
};
return VertexOutputBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.VertexOutputBlock"] = VertexOutputBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/addBlock.ts":
/*!*******************************************!*\
!*** ./Materials/Node/Blocks/addBlock.ts ***!
\*******************************************/
/*! exports provided: AddBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return AddBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to add 2 vectors
*/
var AddBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AddBlock, _super);
/**
* Creates a new AddBlock
* @param name defines the block name
*/
function AddBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
AddBlock.prototype.getClassName = function () {
return "AddBlock";
};
Object.defineProperty(AddBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AddBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(AddBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
AddBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " + " + this.right.associatedVariableName + ";\r\n");
return this;
};
return AddBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.AddBlock"] = AddBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/arcTan2Block.ts":
/*!***********************************************!*\
!*** ./Materials/Node/Blocks/arcTan2Block.ts ***!
\***********************************************/
/*! exports provided: ArcTan2Block */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArcTan2Block", function() { return ArcTan2Block; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to compute arc tangent of 2 values
*/
var ArcTan2Block = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ArcTan2Block, _super);
/**
* Creates a new ArcTan2Block
* @param name defines the block name
*/
function ArcTan2Block(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("x", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerInput("y", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ArcTan2Block.prototype.getClassName = function () {
return "ArcTan2Block";
};
Object.defineProperty(ArcTan2Block.prototype, "x", {
/**
* Gets the x operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcTan2Block.prototype, "y", {
/**
* Gets the y operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ArcTan2Block.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ArcTan2Block.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = atan(" + this.x.associatedVariableName + ", " + this.y.associatedVariableName + ");\r\n");
return this;
};
return ArcTan2Block;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ArcTan2Block"] = ArcTan2Block;
/***/ }),
/***/ "./Materials/Node/Blocks/clampBlock.ts":
/*!*********************************************!*\
!*** ./Materials/Node/Blocks/clampBlock.ts ***!
\*********************************************/
/*! exports provided: ClampBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return ClampBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/**
* Block used to clamp a float
*/
var ClampBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ClampBlock, _super);
/**
* Creates a new ClampBlock
* @param name defines the block name
*/
function ClampBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
/** Gets or sets the minimum range */
_this.minimum = 0.0;
/** Gets or sets the maximum range */
_this.maximum = 1.0;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ClampBlock.prototype.getClassName = function () {
return "ClampBlock";
};
Object.defineProperty(ClampBlock.prototype, "value", {
/**
* Gets the value input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ClampBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ClampBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = clamp(" + this.value.associatedVariableName + ", " + this._writeFloat(this.minimum) + ", " + this._writeFloat(this.maximum) + ");\r\n");
return this;
};
ClampBlock.prototype._dumpPropertiesCode = function () {
var codeString = this._codeVariableName + ".minimum = " + this.minimum + ";\r\n";
codeString += this._codeVariableName + ".maximum = " + this.maximum + ";\r\n";
return codeString;
};
ClampBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.minimum = this.minimum;
serializationObject.maximum = this.maximum;
return serializationObject;
};
ClampBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.minimum = serializationObject.minimum;
this.maximum = serializationObject.maximum;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["editableInPropertyPage"])("Minimum", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["PropertyTypeForEdition"].Float)
], ClampBlock.prototype, "minimum", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["editableInPropertyPage"])("Maximum", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["PropertyTypeForEdition"].Float)
], ClampBlock.prototype, "maximum", void 0);
return ClampBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ClampBlock"] = ClampBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/colorMergerBlock.ts":
/*!***************************************************!*\
!*** ./Materials/Node/Blocks/colorMergerBlock.ts ***!
\***************************************************/
/*! exports provided: ColorMergerBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorMergerBlock", function() { return ColorMergerBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to create a Color3/4 out of individual inputs (one for each component)
*/
var ColorMergerBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ColorMergerBlock, _super);
/**
* Create a new ColorMergerBlock
* @param name defines the block name
*/
function ColorMergerBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("rgb ", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true);
_this.registerInput("r", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("g", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("b", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerOutput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this.registerOutput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ColorMergerBlock.prototype.getClassName = function () {
return "ColorMergerBlock";
};
Object.defineProperty(ColorMergerBlock.prototype, "rgbIn", {
/**
* Gets the rgb component (input)
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "r", {
/**
* Gets the r component (input)
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "g", {
/**
* Gets the g component (input)
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "b", {
/**
* Gets the b component (input)
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "a", {
/**
* Gets the a component (input)
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "rgba", {
/**
* Gets the rgba component (output)
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "rgbOut", {
/**
* Gets the rgb component (output)
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorMergerBlock.prototype, "rgb", {
/**
* Gets the rgb component (output)
* @deprecated Please use rgbOut instead.
*/
get: function () {
return this.rgbOut;
},
enumerable: false,
configurable: true
});
ColorMergerBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var rInput = this.r;
var gInput = this.g;
var bInput = this.b;
var aInput = this.a;
var rgbInput = this.rgbIn;
var color4Output = this._outputs[0];
var color3Output = this._outputs[1];
if (rgbInput.isConnected) {
if (color4Output.hasEndpoints) {
state.compilationString += this._declareOutput(color4Output, state) + (" = vec4(" + rgbInput.associatedVariableName + ", " + (aInput.isConnected ? this._writeVariable(aInput) : "0.0") + ");\r\n");
}
else if (color3Output.hasEndpoints) {
state.compilationString += this._declareOutput(color3Output, state) + (" = " + rgbInput.associatedVariableName + ";\r\n");
}
}
else {
if (color4Output.hasEndpoints) {
state.compilationString += this._declareOutput(color4Output, state) + (" = vec4(" + (rInput.isConnected ? this._writeVariable(rInput) : "0.0") + ", " + (gInput.isConnected ? this._writeVariable(gInput) : "0.0") + ", " + (bInput.isConnected ? this._writeVariable(bInput) : "0.0") + ", " + (aInput.isConnected ? this._writeVariable(aInput) : "0.0") + ");\r\n");
}
else if (color3Output.hasEndpoints) {
state.compilationString += this._declareOutput(color3Output, state) + (" = vec3(" + (rInput.isConnected ? this._writeVariable(rInput) : "0.0") + ", " + (gInput.isConnected ? this._writeVariable(gInput) : "0.0") + ", " + (bInput.isConnected ? this._writeVariable(bInput) : "0.0") + ");\r\n");
}
}
return this;
};
return ColorMergerBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ColorMergerBlock"] = ColorMergerBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/colorSplitterBlock.ts":
/*!*****************************************************!*\
!*** ./Materials/Node/Blocks/colorSplitterBlock.ts ***!
\*****************************************************/
/*! exports provided: ColorSplitterBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorSplitterBlock", function() { return ColorSplitterBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to expand a Color3/4 into 4 outputs (one for each component)
*/
var ColorSplitterBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ColorSplitterBlock, _super);
/**
* Create a new ColorSplitterBlock
* @param name defines the block name
*/
function ColorSplitterBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("rgba", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4, true);
_this.registerInput("rgb ", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3, true);
_this.registerOutput("rgb", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this.registerOutput("r", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("g", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("b", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("a", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.inputsAreExclusive = true;
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ColorSplitterBlock.prototype.getClassName = function () {
return "ColorSplitterBlock";
};
Object.defineProperty(ColorSplitterBlock.prototype, "rgba", {
/**
* Gets the rgba component (input)
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorSplitterBlock.prototype, "rgbIn", {
/**
* Gets the rgb component (input)
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorSplitterBlock.prototype, "rgbOut", {
/**
* Gets the rgb component (output)
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorSplitterBlock.prototype, "r", {
/**
* Gets the r component (output)
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorSplitterBlock.prototype, "g", {
/**
* Gets the g component (output)
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorSplitterBlock.prototype, "b", {
/**
* Gets the b component (output)
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ColorSplitterBlock.prototype, "a", {
/**
* Gets the a component (output)
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
ColorSplitterBlock.prototype._inputRename = function (name) {
if (name === "rgb ") {
return "rgbIn";
}
return name;
};
ColorSplitterBlock.prototype._outputRename = function (name) {
if (name === "rgb") {
return "rgbOut";
}
return name;
};
ColorSplitterBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var input = this.rgba.isConnected ? this.rgba : this.rgbIn;
if (!input.isConnected) {
return;
}
var rgbOutput = this._outputs[0];
var rOutput = this._outputs[1];
var gOutput = this._outputs[2];
var bOutput = this._outputs[3];
var aOutput = this._outputs[4];
if (rgbOutput.hasEndpoints) {
state.compilationString += this._declareOutput(rgbOutput, state) + (" = " + input.associatedVariableName + ".rgb;\r\n");
}
if (rOutput.hasEndpoints) {
state.compilationString += this._declareOutput(rOutput, state) + (" = " + input.associatedVariableName + ".r;\r\n");
}
if (gOutput.hasEndpoints) {
state.compilationString += this._declareOutput(gOutput, state) + (" = " + input.associatedVariableName + ".g;\r\n");
}
if (bOutput.hasEndpoints) {
state.compilationString += this._declareOutput(bOutput, state) + (" = " + input.associatedVariableName + ".b;\r\n");
}
if (aOutput.hasEndpoints) {
state.compilationString += this._declareOutput(aOutput, state) + (" = " + input.associatedVariableName + ".a;\r\n");
}
return this;
};
return ColorSplitterBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ColorSplitterBlock"] = ColorSplitterBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/crossBlock.ts":
/*!*********************************************!*\
!*** ./Materials/Node/Blocks/crossBlock.ts ***!
\*********************************************/
/*! exports provided: CrossBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CrossBlock", function() { return CrossBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to apply a cross product between 2 vectors
*/
var CrossBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CrossBlock, _super);
/**
* Creates a new CrossBlock
* @param name defines the block name
*/
function CrossBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._linkConnectionTypes(0, 1);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
CrossBlock.prototype.getClassName = function () {
return "CrossBlock";
};
Object.defineProperty(CrossBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CrossBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(CrossBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
CrossBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = cross(" + this.left.associatedVariableName + ".xyz, " + this.right.associatedVariableName + ".xyz);\r\n");
return this;
};
return CrossBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.CrossBlock"] = CrossBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/desaturateBlock.ts":
/*!**************************************************!*\
!*** ./Materials/Node/Blocks/desaturateBlock.ts ***!
\**************************************************/
/*! exports provided: DesaturateBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DesaturateBlock", function() { return DesaturateBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to desaturate a color
*/
var DesaturateBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DesaturateBlock, _super);
/**
* Creates a new DesaturateBlock
* @param name defines the block name
*/
function DesaturateBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("color", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this.registerInput("level", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
DesaturateBlock.prototype.getClassName = function () {
return "DesaturateBlock";
};
Object.defineProperty(DesaturateBlock.prototype, "color", {
/**
* Gets the color operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DesaturateBlock.prototype, "level", {
/**
* Gets the level operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DesaturateBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
DesaturateBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var color = this.color;
var colorName = color.associatedVariableName;
var tempMin = state._getFreeVariableName("colorMin");
var tempMax = state._getFreeVariableName("colorMax");
var tempMerge = state._getFreeVariableName("colorMerge");
state.compilationString += "float " + tempMin + " = min(min(" + colorName + ".x, " + colorName + ".y), " + colorName + ".z);\r\n";
state.compilationString += "float " + tempMax + " = max(max(" + colorName + ".x, " + colorName + ".y), " + colorName + ".z);\r\n";
state.compilationString += "float " + tempMerge + " = 0.5 * (" + tempMin + " + " + tempMax + ");\r\n";
state.compilationString += this._declareOutput(output, state) + (" = mix(" + colorName + ", vec3(" + tempMerge + ", " + tempMerge + ", " + tempMerge + "), " + this.level.associatedVariableName + ");\r\n");
return this;
};
return DesaturateBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.DesaturateBlock"] = DesaturateBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/distanceBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/distanceBlock.ts ***!
\************************************************/
/*! exports provided: DistanceBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DistanceBlock", function() { return DistanceBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the distance between 2 values
*/
var DistanceBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DistanceBlock, _super);
/**
* Creates a new DistanceBlock
* @param name defines the block name
*/
function DistanceBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._linkConnectionTypes(0, 1);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
DistanceBlock.prototype.getClassName = function () {
return "DistanceBlock";
};
Object.defineProperty(DistanceBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DistanceBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DistanceBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
DistanceBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = length(" + this.left.associatedVariableName + " - " + this.right.associatedVariableName + ");\r\n");
return this;
};
return DistanceBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.DistanceBlock"] = DistanceBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/divideBlock.ts":
/*!**********************************************!*\
!*** ./Materials/Node/Blocks/divideBlock.ts ***!
\**********************************************/
/*! exports provided: DivideBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DivideBlock", function() { return DivideBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to divide 2 vectors
*/
var DivideBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DivideBlock, _super);
/**
* Creates a new DivideBlock
* @param name defines the block name
*/
function DivideBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
DivideBlock.prototype.getClassName = function () {
return "DivideBlock";
};
Object.defineProperty(DivideBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DivideBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DivideBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
DivideBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " / " + this.right.associatedVariableName + ";\r\n");
return this;
};
return DivideBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.DivideBlock"] = DivideBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/dotBlock.ts":
/*!*******************************************!*\
!*** ./Materials/Node/Blocks/dotBlock.ts ***!
\*******************************************/
/*! exports provided: DotBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DotBlock", function() { return DotBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to apply a dot product between 2 vectors
*/
var DotBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DotBlock, _super);
/**
* Creates a new DotBlock
* @param name defines the block name
*/
function DotBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._linkConnectionTypes(0, 1);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
DotBlock.prototype.getClassName = function () {
return "DotBlock";
};
Object.defineProperty(DotBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DotBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(DotBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
DotBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = dot(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + ");\r\n");
return this;
};
return DotBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.DotBlock"] = DotBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/fresnelBlock.ts":
/*!***********************************************!*\
!*** ./Materials/Node/Blocks/fresnelBlock.ts ***!
\***********************************************/
/*! exports provided: FresnelBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FresnelBlock", function() { return FresnelBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Shaders_ShadersInclude_fresnelFunction__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../Shaders/ShadersInclude/fresnelFunction */ "./Shaders/ShadersInclude/fresnelFunction.ts");
/* harmony import */ var _viewDirectionBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./viewDirectionBlock */ "./Materials/Node/Blocks/viewDirectionBlock.ts");
/**
* Block used to compute fresnel value
*/
var FresnelBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FresnelBlock, _super);
/**
* Create a new FresnelBlock
* @param name defines the block name
*/
function FresnelBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("worldNormal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("viewDirection", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("bias", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerInput("power", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("fresnel", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
FresnelBlock.prototype.getClassName = function () {
return "FresnelBlock";
};
Object.defineProperty(FresnelBlock.prototype, "worldNormal", {
/**
* Gets the world normal input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FresnelBlock.prototype, "viewDirection", {
/**
* Gets the view direction input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FresnelBlock.prototype, "bias", {
/**
* Gets the bias input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FresnelBlock.prototype, "power", {
/**
* Gets the camera (or eye) position component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(FresnelBlock.prototype, "fresnel", {
/**
* Gets the fresnel output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
FresnelBlock.prototype.autoConfigure = function (material) {
if (!this.viewDirection.isConnected) {
var viewDirectionInput = new _viewDirectionBlock__WEBPACK_IMPORTED_MODULE_7__["ViewDirectionBlock"]("View direction");
viewDirectionInput.output.connectTo(this.viewDirection);
viewDirectionInput.autoConfigure(material);
}
if (!this.bias.isConnected) {
var biasInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("bias");
biasInput.value = 0;
biasInput.output.connectTo(this.bias);
}
if (!this.power.isConnected) {
var powerInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("power");
powerInput.value = 1;
powerInput.output.connectTo(this.power);
}
};
FresnelBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var comments = "//" + this.name;
state._emitFunctionFromInclude("fresnelFunction", comments, { removeIfDef: true });
state.compilationString += this._declareOutput(this.fresnel, state) + (" = computeFresnelTerm(" + this.viewDirection.associatedVariableName + ".xyz, " + this.worldNormal.associatedVariableName + ".xyz, " + this.bias.associatedVariableName + ", " + this.power.associatedVariableName + ");\r\n");
return this;
};
return FresnelBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.FresnelBlock"] = FresnelBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/gradientBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/gradientBlock.ts ***!
\************************************************/
/*! exports provided: GradientBlockColorStep, GradientBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GradientBlockColorStep", function() { return GradientBlockColorStep; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GradientBlock", function() { return GradientBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Maths/math.color */ "./Maths/math.color.ts");
/**
* Class used to store a color step for the GradientBlock
*/
var GradientBlockColorStep = /** @class */ (function () {
/**
* Creates a new GradientBlockColorStep
* @param step defines a value indicating which step this color is associated with (between 0 and 1)
* @param color defines the color associated with this step
*/
function GradientBlockColorStep(
/**
* Gets or sets a value indicating which step this color is associated with (between 0 and 1)
*/
step,
/**
* Gets or sets the color associated with this step
*/
color) {
this.step = step;
this.color = color;
}
return GradientBlockColorStep;
}());
/**
* Block used to return a color from a gradient based on an input value between 0 and 1
*/
var GradientBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(GradientBlock, _super);
/**
* Creates a new GradientBlock
* @param name defines the block name
*/
function GradientBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
/**
* Gets or sets the list of color steps
*/
_this.colorSteps = [
new GradientBlockColorStep(0, _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__["Color3"].Black()),
new GradientBlockColorStep(1.0, _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__["Color3"].White())
];
_this.registerInput("gradient", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
GradientBlock.prototype.getClassName = function () {
return "GradientBlock";
};
Object.defineProperty(GradientBlock.prototype, "gradient", {
/**
* Gets the gradient input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(GradientBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
GradientBlock.prototype._writeColorConstant = function (index) {
var step = this.colorSteps[index];
return "vec3(" + step.color.r + ", " + step.color.g + ", " + step.color.b + ")";
};
GradientBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
if (!this.colorSteps.length || !this.gradient.connectedPoint) {
state.compilationString += this._declareOutput(output, state) + " = vec3(0., 0., 0.);\r\n";
return;
}
var tempColor = state._getFreeVariableName("gradientTempColor");
var tempPosition = state._getFreeVariableName("gradientTempPosition");
state.compilationString += "vec3 " + tempColor + " = " + this._writeColorConstant(0) + ";\r\n";
state.compilationString += "float " + tempPosition + ";\r\n";
var gradientSource = this.gradient.associatedVariableName;
if (this.gradient.connectedPoint.type !== _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float) {
gradientSource += ".x";
}
for (var index = 1; index < this.colorSteps.length; index++) {
var step = this.colorSteps[index];
var previousStep = this.colorSteps[index - 1];
state.compilationString += tempPosition + " = clamp((" + gradientSource + " - " + state._emitFloat(previousStep.step) + ") / (" + state._emitFloat(step.step) + " - " + state._emitFloat(previousStep.step) + "), 0.0, 1.0) * step(" + state._emitFloat(index) + ", " + state._emitFloat(this.colorSteps.length - 1) + ");\r\n";
state.compilationString += tempColor + " = mix(" + tempColor + ", " + this._writeColorConstant(index) + ", " + tempPosition + ");\r\n";
}
state.compilationString += this._declareOutput(output, state) + (" = " + tempColor + ";\r\n");
return this;
};
GradientBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.colorSteps = this.colorSteps;
return serializationObject;
};
GradientBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.colorSteps = [];
for (var _i = 0, _a = serializationObject.colorSteps; _i < _a.length; _i++) {
var step = _a[_i];
this.colorSteps.push(new GradientBlockColorStep(step.step, new _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__["Color3"](step.color.r, step.color.g, step.color.b)));
}
};
GradientBlock.prototype._dumpPropertiesCode = function () {
var codeString = "";
for (var _i = 0, _a = this.colorSteps; _i < _a.length; _i++) {
var colorStep = _a[_i];
codeString += this._codeVariableName + ".colorSteps.push(new BABYLON.GradientBlockColorStep(" + colorStep.step + ", new BABYLON.Color3(" + colorStep.color.r + ", " + colorStep.color.g + ", " + colorStep.color.b + ")));\r\n";
}
return codeString;
};
return GradientBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.GradientBlock"] = GradientBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/index.ts":
/*!****************************************!*\
!*** ./Materials/Node/Blocks/index.ts ***!
\****************************************/
/*! exports provided: VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, LightInformationBlock, FragmentOutputBlock, ImageProcessingBlock, PerturbNormalBlock, DiscardBlock, FrontFacingBlock, DerivativeBlock, FragCoordBlock, ScreenSizeBlock, FogBlock, LightBlock, TextureBlock, ReflectionTextureBlock, CurrentScreenBlock, InputBlock, AnimatedInputBlockTypes, MultiplyBlock, AddBlock, ScaleBlock, ClampBlock, CrossBlock, DotBlock, TransformBlock, RemapBlock, NormalizeBlock, TrigonometryBlockOperations, TrigonometryBlock, ColorMergerBlock, VectorMergerBlock, ColorSplitterBlock, VectorSplitterBlock, LerpBlock, DivideBlock, SubtractBlock, StepBlock, OneMinusBlock, ViewDirectionBlock, FresnelBlock, MaxBlock, MinBlock, DistanceBlock, LengthBlock, NegateBlock, PowBlock, RandomNumberBlock, ArcTan2Block, SmoothStepBlock, ReciprocalBlock, ReplaceColorBlock, PosterizeBlock, WaveBlockKind, WaveBlock, GradientBlockColorStep, GradientBlock, NLerpBlock, WorleyNoise3DBlock, SimplexPerlin3DBlock, NormalBlendBlock, Rotate2dBlock, ReflectBlock, RefractBlock, DesaturateBlock, PBRMetallicRoughnessBlock, SheenBlock, AmbientOcclusionBlock, ReflectivityBlock, AnisotropyBlock, ReflectionBlock, ClearCoatBlock, RefractionBlock, SubSurfaceBlock, ParticleTextureBlock, ParticleRampGradientBlock, ParticleBlendMultiplyBlock, ModBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Vertex_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Vertex/index */ "./Materials/Node/Blocks/Vertex/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["VertexOutputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["BonesBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["InstancesBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["MorphTargetsBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightInformationBlock", function() { return _Vertex_index__WEBPACK_IMPORTED_MODULE_0__["LightInformationBlock"]; });
/* harmony import */ var _Fragment_index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Fragment/index */ "./Materials/Node/Blocks/Fragment/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["FragmentOutputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["ImageProcessingBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerturbNormalBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["PerturbNormalBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscardBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["DiscardBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FrontFacingBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["FrontFacingBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DerivativeBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["DerivativeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragCoordBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["FragCoordBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenSizeBlock", function() { return _Fragment_index__WEBPACK_IMPORTED_MODULE_1__["ScreenSizeBlock"]; });
/* harmony import */ var _Dual_index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Dual/index */ "./Materials/Node/Blocks/Dual/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _Dual_index__WEBPACK_IMPORTED_MODULE_2__["FogBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightBlock", function() { return _Dual_index__WEBPACK_IMPORTED_MODULE_2__["LightBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _Dual_index__WEBPACK_IMPORTED_MODULE_2__["TextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionTextureBlock", function() { return _Dual_index__WEBPACK_IMPORTED_MODULE_2__["ReflectionTextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CurrentScreenBlock", function() { return _Dual_index__WEBPACK_IMPORTED_MODULE_2__["CurrentScreenBlock"]; });
/* harmony import */ var _Input_index__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./Input/index */ "./Materials/Node/Blocks/Input/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputBlock", function() { return _Input_index__WEBPACK_IMPORTED_MODULE_3__["InputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimatedInputBlockTypes", function() { return _Input_index__WEBPACK_IMPORTED_MODULE_3__["AnimatedInputBlockTypes"]; });
/* harmony import */ var _multiplyBlock__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./multiplyBlock */ "./Materials/Node/Blocks/multiplyBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _multiplyBlock__WEBPACK_IMPORTED_MODULE_4__["MultiplyBlock"]; });
/* harmony import */ var _addBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./addBlock */ "./Materials/Node/Blocks/addBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _addBlock__WEBPACK_IMPORTED_MODULE_5__["AddBlock"]; });
/* harmony import */ var _scaleBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./scaleBlock */ "./Materials/Node/Blocks/scaleBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleBlock", function() { return _scaleBlock__WEBPACK_IMPORTED_MODULE_6__["ScaleBlock"]; });
/* harmony import */ var _clampBlock__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./clampBlock */ "./Materials/Node/Blocks/clampBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _clampBlock__WEBPACK_IMPORTED_MODULE_7__["ClampBlock"]; });
/* harmony import */ var _crossBlock__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./crossBlock */ "./Materials/Node/Blocks/crossBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CrossBlock", function() { return _crossBlock__WEBPACK_IMPORTED_MODULE_8__["CrossBlock"]; });
/* harmony import */ var _dotBlock__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./dotBlock */ "./Materials/Node/Blocks/dotBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DotBlock", function() { return _dotBlock__WEBPACK_IMPORTED_MODULE_9__["DotBlock"]; });
/* harmony import */ var _transformBlock__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./transformBlock */ "./Materials/Node/Blocks/transformBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformBlock", function() { return _transformBlock__WEBPACK_IMPORTED_MODULE_10__["TransformBlock"]; });
/* harmony import */ var _remapBlock__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./remapBlock */ "./Materials/Node/Blocks/remapBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RemapBlock", function() { return _remapBlock__WEBPACK_IMPORTED_MODULE_11__["RemapBlock"]; });
/* harmony import */ var _normalizeBlock__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./normalizeBlock */ "./Materials/Node/Blocks/normalizeBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NormalizeBlock", function() { return _normalizeBlock__WEBPACK_IMPORTED_MODULE_12__["NormalizeBlock"]; });
/* harmony import */ var _trigonometryBlock__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./trigonometryBlock */ "./Materials/Node/Blocks/trigonometryBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlockOperations", function() { return _trigonometryBlock__WEBPACK_IMPORTED_MODULE_13__["TrigonometryBlockOperations"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlock", function() { return _trigonometryBlock__WEBPACK_IMPORTED_MODULE_13__["TrigonometryBlock"]; });
/* harmony import */ var _colorMergerBlock__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./colorMergerBlock */ "./Materials/Node/Blocks/colorMergerBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorMergerBlock", function() { return _colorMergerBlock__WEBPACK_IMPORTED_MODULE_14__["ColorMergerBlock"]; });
/* harmony import */ var _vectorMergerBlock__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./vectorMergerBlock */ "./Materials/Node/Blocks/vectorMergerBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VectorMergerBlock", function() { return _vectorMergerBlock__WEBPACK_IMPORTED_MODULE_15__["VectorMergerBlock"]; });
/* harmony import */ var _colorSplitterBlock__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./colorSplitterBlock */ "./Materials/Node/Blocks/colorSplitterBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorSplitterBlock", function() { return _colorSplitterBlock__WEBPACK_IMPORTED_MODULE_16__["ColorSplitterBlock"]; });
/* harmony import */ var _vectorSplitterBlock__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./vectorSplitterBlock */ "./Materials/Node/Blocks/vectorSplitterBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VectorSplitterBlock", function() { return _vectorSplitterBlock__WEBPACK_IMPORTED_MODULE_17__["VectorSplitterBlock"]; });
/* harmony import */ var _lerpBlock__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ./lerpBlock */ "./Materials/Node/Blocks/lerpBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LerpBlock", function() { return _lerpBlock__WEBPACK_IMPORTED_MODULE_18__["LerpBlock"]; });
/* harmony import */ var _divideBlock__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./divideBlock */ "./Materials/Node/Blocks/divideBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DivideBlock", function() { return _divideBlock__WEBPACK_IMPORTED_MODULE_19__["DivideBlock"]; });
/* harmony import */ var _subtractBlock__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./subtractBlock */ "./Materials/Node/Blocks/subtractBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubtractBlock", function() { return _subtractBlock__WEBPACK_IMPORTED_MODULE_20__["SubtractBlock"]; });
/* harmony import */ var _stepBlock__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./stepBlock */ "./Materials/Node/Blocks/stepBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StepBlock", function() { return _stepBlock__WEBPACK_IMPORTED_MODULE_21__["StepBlock"]; });
/* harmony import */ var _oneMinusBlock__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./oneMinusBlock */ "./Materials/Node/Blocks/oneMinusBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OneMinusBlock", function() { return _oneMinusBlock__WEBPACK_IMPORTED_MODULE_22__["OneMinusBlock"]; });
/* harmony import */ var _viewDirectionBlock__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ./viewDirectionBlock */ "./Materials/Node/Blocks/viewDirectionBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViewDirectionBlock", function() { return _viewDirectionBlock__WEBPACK_IMPORTED_MODULE_23__["ViewDirectionBlock"]; });
/* harmony import */ var _fresnelBlock__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ./fresnelBlock */ "./Materials/Node/Blocks/fresnelBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelBlock", function() { return _fresnelBlock__WEBPACK_IMPORTED_MODULE_24__["FresnelBlock"]; });
/* harmony import */ var _maxBlock__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ./maxBlock */ "./Materials/Node/Blocks/maxBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaxBlock", function() { return _maxBlock__WEBPACK_IMPORTED_MODULE_25__["MaxBlock"]; });
/* harmony import */ var _minBlock__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ./minBlock */ "./Materials/Node/Blocks/minBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MinBlock", function() { return _minBlock__WEBPACK_IMPORTED_MODULE_26__["MinBlock"]; });
/* harmony import */ var _distanceBlock__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ./distanceBlock */ "./Materials/Node/Blocks/distanceBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DistanceBlock", function() { return _distanceBlock__WEBPACK_IMPORTED_MODULE_27__["DistanceBlock"]; });
/* harmony import */ var _lengthBlock__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./lengthBlock */ "./Materials/Node/Blocks/lengthBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LengthBlock", function() { return _lengthBlock__WEBPACK_IMPORTED_MODULE_28__["LengthBlock"]; });
/* harmony import */ var _negateBlock__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./negateBlock */ "./Materials/Node/Blocks/negateBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NegateBlock", function() { return _negateBlock__WEBPACK_IMPORTED_MODULE_29__["NegateBlock"]; });
/* harmony import */ var _powBlock__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./powBlock */ "./Materials/Node/Blocks/powBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowBlock", function() { return _powBlock__WEBPACK_IMPORTED_MODULE_30__["PowBlock"]; });
/* harmony import */ var _randomNumberBlock__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./randomNumberBlock */ "./Materials/Node/Blocks/randomNumberBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RandomNumberBlock", function() { return _randomNumberBlock__WEBPACK_IMPORTED_MODULE_31__["RandomNumberBlock"]; });
/* harmony import */ var _arcTan2Block__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ./arcTan2Block */ "./Materials/Node/Blocks/arcTan2Block.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcTan2Block", function() { return _arcTan2Block__WEBPACK_IMPORTED_MODULE_32__["ArcTan2Block"]; });
/* harmony import */ var _smoothStepBlock__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ./smoothStepBlock */ "./Materials/Node/Blocks/smoothStepBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmoothStepBlock", function() { return _smoothStepBlock__WEBPACK_IMPORTED_MODULE_33__["SmoothStepBlock"]; });
/* harmony import */ var _reciprocalBlock__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./reciprocalBlock */ "./Materials/Node/Blocks/reciprocalBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReciprocalBlock", function() { return _reciprocalBlock__WEBPACK_IMPORTED_MODULE_34__["ReciprocalBlock"]; });
/* harmony import */ var _replaceColorBlock__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ./replaceColorBlock */ "./Materials/Node/Blocks/replaceColorBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReplaceColorBlock", function() { return _replaceColorBlock__WEBPACK_IMPORTED_MODULE_35__["ReplaceColorBlock"]; });
/* harmony import */ var _posterizeBlock__WEBPACK_IMPORTED_MODULE_36__ = __webpack_require__(/*! ./posterizeBlock */ "./Materials/Node/Blocks/posterizeBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PosterizeBlock", function() { return _posterizeBlock__WEBPACK_IMPORTED_MODULE_36__["PosterizeBlock"]; });
/* harmony import */ var _waveBlock__WEBPACK_IMPORTED_MODULE_37__ = __webpack_require__(/*! ./waveBlock */ "./Materials/Node/Blocks/waveBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WaveBlockKind", function() { return _waveBlock__WEBPACK_IMPORTED_MODULE_37__["WaveBlockKind"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WaveBlock", function() { return _waveBlock__WEBPACK_IMPORTED_MODULE_37__["WaveBlock"]; });
/* harmony import */ var _gradientBlock__WEBPACK_IMPORTED_MODULE_38__ = __webpack_require__(/*! ./gradientBlock */ "./Materials/Node/Blocks/gradientBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientBlockColorStep", function() { return _gradientBlock__WEBPACK_IMPORTED_MODULE_38__["GradientBlockColorStep"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientBlock", function() { return _gradientBlock__WEBPACK_IMPORTED_MODULE_38__["GradientBlock"]; });
/* harmony import */ var _nLerpBlock__WEBPACK_IMPORTED_MODULE_39__ = __webpack_require__(/*! ./nLerpBlock */ "./Materials/Node/Blocks/nLerpBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NLerpBlock", function() { return _nLerpBlock__WEBPACK_IMPORTED_MODULE_39__["NLerpBlock"]; });
/* harmony import */ var _worleyNoise3DBlock__WEBPACK_IMPORTED_MODULE_40__ = __webpack_require__(/*! ./worleyNoise3DBlock */ "./Materials/Node/Blocks/worleyNoise3DBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WorleyNoise3DBlock", function() { return _worleyNoise3DBlock__WEBPACK_IMPORTED_MODULE_40__["WorleyNoise3DBlock"]; });
/* harmony import */ var _simplexPerlin3DBlock__WEBPACK_IMPORTED_MODULE_41__ = __webpack_require__(/*! ./simplexPerlin3DBlock */ "./Materials/Node/Blocks/simplexPerlin3DBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplexPerlin3DBlock", function() { return _simplexPerlin3DBlock__WEBPACK_IMPORTED_MODULE_41__["SimplexPerlin3DBlock"]; });
/* harmony import */ var _normalBlendBlock__WEBPACK_IMPORTED_MODULE_42__ = __webpack_require__(/*! ./normalBlendBlock */ "./Materials/Node/Blocks/normalBlendBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NormalBlendBlock", function() { return _normalBlendBlock__WEBPACK_IMPORTED_MODULE_42__["NormalBlendBlock"]; });
/* harmony import */ var _rotate2dBlock__WEBPACK_IMPORTED_MODULE_43__ = __webpack_require__(/*! ./rotate2dBlock */ "./Materials/Node/Blocks/rotate2dBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rotate2dBlock", function() { return _rotate2dBlock__WEBPACK_IMPORTED_MODULE_43__["Rotate2dBlock"]; });
/* harmony import */ var _reflectBlock__WEBPACK_IMPORTED_MODULE_44__ = __webpack_require__(/*! ./reflectBlock */ "./Materials/Node/Blocks/reflectBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectBlock", function() { return _reflectBlock__WEBPACK_IMPORTED_MODULE_44__["ReflectBlock"]; });
/* harmony import */ var _refractBlock__WEBPACK_IMPORTED_MODULE_45__ = __webpack_require__(/*! ./refractBlock */ "./Materials/Node/Blocks/refractBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractBlock", function() { return _refractBlock__WEBPACK_IMPORTED_MODULE_45__["RefractBlock"]; });
/* harmony import */ var _desaturateBlock__WEBPACK_IMPORTED_MODULE_46__ = __webpack_require__(/*! ./desaturateBlock */ "./Materials/Node/Blocks/desaturateBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DesaturateBlock", function() { return _desaturateBlock__WEBPACK_IMPORTED_MODULE_46__["DesaturateBlock"]; });
/* harmony import */ var _PBR_index__WEBPACK_IMPORTED_MODULE_47__ = __webpack_require__(/*! ./PBR/index */ "./Materials/Node/Blocks/PBR/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["PBRMetallicRoughnessBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SheenBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["SheenBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmbientOcclusionBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["AmbientOcclusionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectivityBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["ReflectivityBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnisotropyBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["AnisotropyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["ReflectionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClearCoatBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["ClearCoatBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["RefractionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubSurfaceBlock", function() { return _PBR_index__WEBPACK_IMPORTED_MODULE_47__["SubSurfaceBlock"]; });
/* harmony import */ var _Particle_index__WEBPACK_IMPORTED_MODULE_48__ = __webpack_require__(/*! ./Particle/index */ "./Materials/Node/Blocks/Particle/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleTextureBlock", function() { return _Particle_index__WEBPACK_IMPORTED_MODULE_48__["ParticleTextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleRampGradientBlock", function() { return _Particle_index__WEBPACK_IMPORTED_MODULE_48__["ParticleRampGradientBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleBlendMultiplyBlock", function() { return _Particle_index__WEBPACK_IMPORTED_MODULE_48__["ParticleBlendMultiplyBlock"]; });
/* harmony import */ var _modBlock__WEBPACK_IMPORTED_MODULE_49__ = __webpack_require__(/*! ./modBlock */ "./Materials/Node/Blocks/modBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModBlock", function() { return _modBlock__WEBPACK_IMPORTED_MODULE_49__["ModBlock"]; });
/***/ }),
/***/ "./Materials/Node/Blocks/lengthBlock.ts":
/*!**********************************************!*\
!*** ./Materials/Node/Blocks/lengthBlock.ts ***!
\**********************************************/
/*! exports provided: LengthBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LengthBlock", function() { return LengthBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the length of a vector
*/
var LengthBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LengthBlock, _super);
/**
* Creates a new LengthBlock
* @param name defines the block name
*/
function LengthBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
LengthBlock.prototype.getClassName = function () {
return "LengthBlock";
};
Object.defineProperty(LengthBlock.prototype, "value", {
/**
* Gets the value input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LengthBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
LengthBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = length(" + this.value.associatedVariableName + ");\r\n");
return this;
};
return LengthBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.LengthBlock"] = LengthBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/lerpBlock.ts":
/*!********************************************!*\
!*** ./Materials/Node/Blocks/lerpBlock.ts ***!
\********************************************/
/*! exports provided: LerpBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LerpBlock", function() { return LerpBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to lerp between 2 values
*/
var LerpBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LerpBlock, _super);
/**
* Creates a new LerpBlock
* @param name defines the block name
*/
function LerpBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("gradient", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
_this._linkConnectionTypes(1, 2);
_this._inputs[2].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
LerpBlock.prototype.getClassName = function () {
return "LerpBlock";
};
Object.defineProperty(LerpBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LerpBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LerpBlock.prototype, "gradient", {
/**
* Gets the gradient operand input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(LerpBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
LerpBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = mix(" + this.left.associatedVariableName + " , " + this.right.associatedVariableName + ", " + this.gradient.associatedVariableName + ");\r\n");
return this;
};
return LerpBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.LerpBlock"] = LerpBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/maxBlock.ts":
/*!*******************************************!*\
!*** ./Materials/Node/Blocks/maxBlock.ts ***!
\*******************************************/
/*! exports provided: MaxBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MaxBlock", function() { return MaxBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the max of 2 values
*/
var MaxBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MaxBlock, _super);
/**
* Creates a new MaxBlock
* @param name defines the block name
*/
function MaxBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
MaxBlock.prototype.getClassName = function () {
return "MaxBlock";
};
Object.defineProperty(MaxBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MaxBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MaxBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
MaxBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = max(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + ");\r\n");
return this;
};
return MaxBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.MaxBlock"] = MaxBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/minBlock.ts":
/*!*******************************************!*\
!*** ./Materials/Node/Blocks/minBlock.ts ***!
\*******************************************/
/*! exports provided: MinBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MinBlock", function() { return MinBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the min of 2 values
*/
var MinBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MinBlock, _super);
/**
* Creates a new MinBlock
* @param name defines the block name
*/
function MinBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
MinBlock.prototype.getClassName = function () {
return "MinBlock";
};
Object.defineProperty(MinBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MinBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MinBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
MinBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = min(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + ");\r\n");
return this;
};
return MinBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.MinBlock"] = MinBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/modBlock.ts":
/*!*******************************************!*\
!*** ./Materials/Node/Blocks/modBlock.ts ***!
\*******************************************/
/*! exports provided: ModBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ModBlock", function() { return ModBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to compute value of one parameter modulo another
*/
var ModBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ModBlock, _super);
/**
* Creates a new ModBlock
* @param name defines the block name
*/
function ModBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ModBlock.prototype.getClassName = function () {
return "ModBlock";
};
Object.defineProperty(ModBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ModBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ModBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ModBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = mod(" + this.left.associatedVariableName + ", " + this.right.associatedVariableName + ");\r\n");
return this;
};
return ModBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ModBlock"] = ModBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/multiplyBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/multiplyBlock.ts ***!
\************************************************/
/*! exports provided: MultiplyBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return MultiplyBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to multiply 2 values
*/
var MultiplyBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MultiplyBlock, _super);
/**
* Creates a new MultiplyBlock
* @param name defines the block name
*/
function MultiplyBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
MultiplyBlock.prototype.getClassName = function () {
return "MultiplyBlock";
};
Object.defineProperty(MultiplyBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MultiplyBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(MultiplyBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
MultiplyBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " * " + this.right.associatedVariableName + ";\r\n");
return this;
};
return MultiplyBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.MultiplyBlock"] = MultiplyBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/nLerpBlock.ts":
/*!*********************************************!*\
!*** ./Materials/Node/Blocks/nLerpBlock.ts ***!
\*********************************************/
/*! exports provided: NLerpBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NLerpBlock", function() { return NLerpBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to normalize lerp between 2 values
*/
var NLerpBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NLerpBlock, _super);
/**
* Creates a new NLerpBlock
* @param name defines the block name
*/
function NLerpBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("gradient", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
NLerpBlock.prototype.getClassName = function () {
return "NLerpBlock";
};
Object.defineProperty(NLerpBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NLerpBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NLerpBlock.prototype, "gradient", {
/**
* Gets the gradient operand input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NLerpBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
NLerpBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = normalize(mix(" + this.left.associatedVariableName + " , " + this.right.associatedVariableName + ", " + this.gradient.associatedVariableName + "));\r\n");
return this;
};
return NLerpBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.NLerpBlock"] = NLerpBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/negateBlock.ts":
/*!**********************************************!*\
!*** ./Materials/Node/Blocks/negateBlock.ts ***!
\**********************************************/
/*! exports provided: NegateBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NegateBlock", function() { return NegateBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get negative version of a value (i.e. x * -1)
*/
var NegateBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NegateBlock, _super);
/**
* Creates a new NegateBlock
* @param name defines the block name
*/
function NegateBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
NegateBlock.prototype.getClassName = function () {
return "NegateBlock";
};
Object.defineProperty(NegateBlock.prototype, "value", {
/**
* Gets the value input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NegateBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
NegateBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = -1.0 * " + this.value.associatedVariableName + ";\r\n");
return this;
};
return NegateBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.NegateBlock"] = NegateBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/normalBlendBlock.ts":
/*!***************************************************!*\
!*** ./Materials/Node/Blocks/normalBlendBlock.ts ***!
\***************************************************/
/*! exports provided: NormalBlendBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NormalBlendBlock", function() { return NormalBlendBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to blend normals
*/
var NormalBlendBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NormalBlendBlock, _super);
/**
* Creates a new NormalBlendBlock
* @param name defines the block name
*/
function NormalBlendBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("normalMap0", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("normalMap1", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
NormalBlendBlock.prototype.getClassName = function () {
return "NormalBlendBlock";
};
Object.defineProperty(NormalBlendBlock.prototype, "normalMap0", {
/**
* Gets the first input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NormalBlendBlock.prototype, "normalMap1", {
/**
* Gets the second input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NormalBlendBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
NormalBlendBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var input0 = this._inputs[0];
var input1 = this._inputs[1];
var stepR = state._getFreeVariableName("stepR");
var stepG = state._getFreeVariableName("stepG");
state.compilationString += "float " + stepR + " = step(0.5, " + input0.associatedVariableName + ".r);\r\n";
state.compilationString += "float " + stepG + " = step(0.5, " + input0.associatedVariableName + ".g);\r\n";
state.compilationString += this._declareOutput(output, state) + ";\r\n";
state.compilationString += output.associatedVariableName + ".r = (1.0 - " + stepR + ") * " + input0.associatedVariableName + ".r * " + input1.associatedVariableName + ".r * 2.0 + " + stepR + " * (1.0 - " + input0.associatedVariableName + ".r) * (1.0 - " + input1.associatedVariableName + ".r) * 2.0;\r\n";
state.compilationString += output.associatedVariableName + ".g = (1.0 - " + stepG + ") * " + input0.associatedVariableName + ".g * " + input1.associatedVariableName + ".g * 2.0 + " + stepG + " * (1.0 - " + input0.associatedVariableName + ".g) * (1.0 - " + input1.associatedVariableName + ".g) * 2.0;\r\n";
state.compilationString += output.associatedVariableName + ".b = " + input0.associatedVariableName + ".b * " + input1.associatedVariableName + ".b;\r\n";
return this;
};
return NormalBlendBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.NormalBlendBlock"] = NormalBlendBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/normalizeBlock.ts":
/*!*************************************************!*\
!*** ./Materials/Node/Blocks/normalizeBlock.ts ***!
\*************************************************/
/*! exports provided: NormalizeBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NormalizeBlock", function() { return NormalizeBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to normalize a vector
*/
var NormalizeBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NormalizeBlock, _super);
/**
* Creates a new NormalizeBlock
* @param name defines the block name
*/
function NormalizeBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
NormalizeBlock.prototype.getClassName = function () {
return "NormalizeBlock";
};
Object.defineProperty(NormalizeBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(NormalizeBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
NormalizeBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var input = this._inputs[0];
state.compilationString += this._declareOutput(output, state) + (" = normalize(" + input.associatedVariableName + ");\r\n");
return this;
};
return NormalizeBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.NormalizeBlock"] = NormalizeBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/oneMinusBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/oneMinusBlock.ts ***!
\************************************************/
/*! exports provided: OneMinusBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OneMinusBlock", function() { return OneMinusBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the opposite (1 - x) of a value
*/
var OneMinusBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(OneMinusBlock, _super);
/**
* Creates a new OneMinusBlock
* @param name defines the block name
*/
function OneMinusBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._outputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
OneMinusBlock.prototype.getClassName = function () {
return "OneMinusBlock";
};
Object.defineProperty(OneMinusBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(OneMinusBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
OneMinusBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = 1. - " + this.input.associatedVariableName + ";\r\n");
return this;
};
return OneMinusBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.OneMinusBlock"] = OneMinusBlock;
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.OppositeBlock"] = OneMinusBlock; // Backward compatibility
/***/ }),
/***/ "./Materials/Node/Blocks/posterizeBlock.ts":
/*!*************************************************!*\
!*** ./Materials/Node/Blocks/posterizeBlock.ts ***!
\*************************************************/
/*! exports provided: PosterizeBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PosterizeBlock", function() { return PosterizeBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to posterize a value
* @see https://en.wikipedia.org/wiki/Posterization
*/
var PosterizeBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PosterizeBlock, _super);
/**
* Creates a new PosterizeBlock
* @param name defines the block name
*/
function PosterizeBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("steps", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
PosterizeBlock.prototype.getClassName = function () {
return "PosterizeBlock";
};
Object.defineProperty(PosterizeBlock.prototype, "value", {
/**
* Gets the value input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PosterizeBlock.prototype, "steps", {
/**
* Gets the steps input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PosterizeBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
PosterizeBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = floor(" + this.value.associatedVariableName + " / (1.0 / " + this.steps.associatedVariableName + ")) * (1.0 / " + this.steps.associatedVariableName + ");\r\n");
return this;
};
return PosterizeBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.PosterizeBlock"] = PosterizeBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/powBlock.ts":
/*!*******************************************!*\
!*** ./Materials/Node/Blocks/powBlock.ts ***!
\*******************************************/
/*! exports provided: PowBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PowBlock", function() { return PowBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the value of the first parameter raised to the power of the second
*/
var PowBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PowBlock, _super);
/**
* Creates a new PowBlock
* @param name defines the block name
*/
function PowBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("power", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
PowBlock.prototype.getClassName = function () {
return "PowBlock";
};
Object.defineProperty(PowBlock.prototype, "value", {
/**
* Gets the value operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PowBlock.prototype, "power", {
/**
* Gets the power operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(PowBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
PowBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = pow(" + this.value.associatedVariableName + ", " + this.power.associatedVariableName + ");\r\n");
return this;
};
return PowBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.PowBlock"] = PowBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/randomNumberBlock.ts":
/*!****************************************************!*\
!*** ./Materials/Node/Blocks/randomNumberBlock.ts ***!
\****************************************************/
/*! exports provided: RandomNumberBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RandomNumberBlock", function() { return RandomNumberBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Shaders_ShadersInclude_helperFunctions__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Shaders/ShadersInclude/helperFunctions */ "./Shaders/ShadersInclude/helperFunctions.ts");
/**
* Block used to get a random number
*/
var RandomNumberBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RandomNumberBlock, _super);
/**
* Creates a new RandomNumberBlock
* @param name defines the block name
*/
function RandomNumberBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("seed", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
RandomNumberBlock.prototype.getClassName = function () {
return "RandomNumberBlock";
};
Object.defineProperty(RandomNumberBlock.prototype, "seed", {
/**
* Gets the seed input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RandomNumberBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
RandomNumberBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var comments = "//" + this.name;
state._emitFunctionFromInclude("helperFunctions", comments);
state.compilationString += this._declareOutput(output, state) + (" = getRand(" + this.seed.associatedVariableName + ".xy);\r\n");
return this;
};
return RandomNumberBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.RandomNumberBlock"] = RandomNumberBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/reciprocalBlock.ts":
/*!**************************************************!*\
!*** ./Materials/Node/Blocks/reciprocalBlock.ts ***!
\**************************************************/
/*! exports provided: ReciprocalBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReciprocalBlock", function() { return ReciprocalBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the reciprocal (1 / x) of a value
*/
var ReciprocalBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReciprocalBlock, _super);
/**
* Creates a new ReciprocalBlock
* @param name defines the block name
*/
function ReciprocalBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._outputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ReciprocalBlock.prototype.getClassName = function () {
return "ReciprocalBlock";
};
Object.defineProperty(ReciprocalBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReciprocalBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ReciprocalBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = 1. / " + this.input.associatedVariableName + ";\r\n");
return this;
};
return ReciprocalBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ReciprocalBlock"] = ReciprocalBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/reflectBlock.ts":
/*!***********************************************!*\
!*** ./Materials/Node/Blocks/reflectBlock.ts ***!
\***********************************************/
/*! exports provided: ReflectBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReflectBlock", function() { return ReflectBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the reflected vector from a direction and a normal
*/
var ReflectBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReflectBlock, _super);
/**
* Creates a new ReflectBlock
* @param name defines the block name
*/
function ReflectBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("incident", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("normal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ReflectBlock.prototype.getClassName = function () {
return "ReflectBlock";
};
Object.defineProperty(ReflectBlock.prototype, "incident", {
/**
* Gets the incident component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectBlock.prototype, "normal", {
/**
* Gets the normal component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReflectBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ReflectBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = reflect(" + this.incident.associatedVariableName + ".xyz, " + this.normal.associatedVariableName + ".xyz);\r\n");
return this;
};
return ReflectBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ReflectBlock"] = ReflectBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/refractBlock.ts":
/*!***********************************************!*\
!*** ./Materials/Node/Blocks/refractBlock.ts ***!
\***********************************************/
/*! exports provided: RefractBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefractBlock", function() { return RefractBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to get the refracted vector from a direction and a normal
*/
var RefractBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RefractBlock, _super);
/**
* Creates a new RefractBlock
* @param name defines the block name
*/
function RefractBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("incident", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("normal", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("ior", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[0].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3);
_this._inputs[1].acceptedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color4);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
RefractBlock.prototype.getClassName = function () {
return "RefractBlock";
};
Object.defineProperty(RefractBlock.prototype, "incident", {
/**
* Gets the incident component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractBlock.prototype, "normal", {
/**
* Gets the normal component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractBlock.prototype, "ior", {
/**
* Gets the index of refraction component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RefractBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
RefractBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = refract(" + this.incident.associatedVariableName + ".xyz, " + this.normal.associatedVariableName + ".xyz, " + this.ior.associatedVariableName + ");\r\n");
return this;
};
return RefractBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.RefractBlock"] = RefractBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/remapBlock.ts":
/*!*********************************************!*\
!*** ./Materials/Node/Blocks/remapBlock.ts ***!
\*********************************************/
/*! exports provided: RemapBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RemapBlock", function() { return RemapBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/**
* Block used to remap a float from a range to a new one
*/
var RemapBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RemapBlock, _super);
/**
* Creates a new RemapBlock
* @param name defines the block name
*/
function RemapBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
/**
* Gets or sets the source range
*/
_this.sourceRange = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector2"](-1, 1);
/**
* Gets or sets the target range
*/
_this.targetRange = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector2"](0, 1);
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("sourceMin", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("sourceMax", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("targetMin", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("targetMax", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
RemapBlock.prototype.getClassName = function () {
return "RemapBlock";
};
Object.defineProperty(RemapBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RemapBlock.prototype, "sourceMin", {
/**
* Gets the source min input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RemapBlock.prototype, "sourceMax", {
/**
* Gets the source max input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RemapBlock.prototype, "targetMin", {
/**
* Gets the target min input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RemapBlock.prototype, "targetMax", {
/**
* Gets the target max input component
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(RemapBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
RemapBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var sourceMin = this.sourceMin.isConnected ? this.sourceMin.associatedVariableName : this._writeFloat(this.sourceRange.x);
var sourceMax = this.sourceMax.isConnected ? this.sourceMax.associatedVariableName : this._writeFloat(this.sourceRange.y);
var targetMin = this.targetMin.isConnected ? this.targetMin.associatedVariableName : this._writeFloat(this.targetRange.x);
var targetMax = this.targetMax.isConnected ? this.targetMax.associatedVariableName : this._writeFloat(this.targetRange.y);
state.compilationString += this._declareOutput(output, state) + (" = " + targetMin + " + (" + this._inputs[0].associatedVariableName + " - " + sourceMin + ") * (" + targetMax + " - " + targetMin + ") / (" + sourceMax + " - " + sourceMin + ");\r\n");
return this;
};
RemapBlock.prototype._dumpPropertiesCode = function () {
var codeString = this._codeVariableName + ".sourceRange = new BABYLON.Vector2(" + this.sourceRange.x + ", " + this.sourceRange.y + ");\r\n";
codeString += this._codeVariableName + ".targetRange = new BABYLON.Vector2(" + this.targetRange.x + ", " + this.targetRange.y + ");\r\n";
return codeString;
};
RemapBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.sourceRange = this.sourceRange.asArray();
serializationObject.targetRange = this.targetRange.asArray();
return serializationObject;
};
RemapBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.sourceRange = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector2"].FromArray(serializationObject.sourceRange);
this.targetRange = _Maths_math_vector__WEBPACK_IMPORTED_MODULE_5__["Vector2"].FromArray(serializationObject.targetRange);
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("From", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Vector2)
], RemapBlock.prototype, "sourceRange", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"])("To", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"].Vector2)
], RemapBlock.prototype, "targetRange", void 0);
return RemapBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.RemapBlock"] = RemapBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/replaceColorBlock.ts":
/*!****************************************************!*\
!*** ./Materials/Node/Blocks/replaceColorBlock.ts ***!
\****************************************************/
/*! exports provided: ReplaceColorBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReplaceColorBlock", function() { return ReplaceColorBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to replace a color by another one
*/
var ReplaceColorBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReplaceColorBlock, _super);
/**
* Creates a new ReplaceColorBlock
* @param name defines the block name
*/
function ReplaceColorBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("reference", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("distance", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerInput("replacement", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
_this._linkConnectionTypes(0, 3);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[1].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this._inputs[3].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this._inputs[3].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ReplaceColorBlock.prototype.getClassName = function () {
return "ReplaceColorBlock";
};
Object.defineProperty(ReplaceColorBlock.prototype, "value", {
/**
* Gets the value input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReplaceColorBlock.prototype, "reference", {
/**
* Gets the reference input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReplaceColorBlock.prototype, "distance", {
/**
* Gets the distance input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReplaceColorBlock.prototype, "replacement", {
/**
* Gets the replacement input component
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ReplaceColorBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ReplaceColorBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + ";\r\n";
state.compilationString += "if (length(" + this.value.associatedVariableName + " - " + this.reference.associatedVariableName + ") < " + this.distance.associatedVariableName + ") {\r\n";
state.compilationString += output.associatedVariableName + " = " + this.replacement.associatedVariableName + ";\r\n";
state.compilationString += "} else {\r\n";
state.compilationString += output.associatedVariableName + " = " + this.value.associatedVariableName + ";\r\n";
state.compilationString += "}\r\n";
return this;
};
return ReplaceColorBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ReplaceColorBlock"] = ReplaceColorBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/rotate2dBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/rotate2dBlock.ts ***!
\************************************************/
/*! exports provided: Rotate2dBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Rotate2dBlock", function() { return Rotate2dBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/**
* Block used to rotate a 2d vector by a given angle
*/
var Rotate2dBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Rotate2dBlock, _super);
/**
* Creates a new Rotate2dBlock
* @param name defines the block name
*/
function Rotate2dBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
_this.registerInput("angle", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
Rotate2dBlock.prototype.getClassName = function () {
return "Rotate2dBlock";
};
Object.defineProperty(Rotate2dBlock.prototype, "input", {
/**
* Gets the input vector
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(Rotate2dBlock.prototype, "angle", {
/**
* Gets the input angle
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(Rotate2dBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Rotate2dBlock.prototype.autoConfigure = function (material) {
if (!this.angle.isConnected) {
var angleInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_5__["InputBlock"]("angle");
angleInput.value = 0;
angleInput.output.connectTo(this.angle);
}
};
Rotate2dBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var angle = this.angle;
var input = this.input;
state.compilationString += this._declareOutput(output, state) + (" = vec2(cos(" + angle.associatedVariableName + ") * " + input.associatedVariableName + ".x - sin(" + angle.associatedVariableName + ") * " + input.associatedVariableName + ".y, sin(" + angle.associatedVariableName + ") * " + input.associatedVariableName + ".x + cos(" + angle.associatedVariableName + ") * " + input.associatedVariableName + ".y);\r\n");
return this;
};
return Rotate2dBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.Rotate2dBlock"] = Rotate2dBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/scaleBlock.ts":
/*!*********************************************!*\
!*** ./Materials/Node/Blocks/scaleBlock.ts ***!
\*********************************************/
/*! exports provided: ScaleBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScaleBlock", function() { return ScaleBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to scale a vector by a float
*/
var ScaleBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ScaleBlock, _super);
/**
* Creates a new ScaleBlock
* @param name defines the block name
*/
function ScaleBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("factor", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ScaleBlock.prototype.getClassName = function () {
return "ScaleBlock";
};
Object.defineProperty(ScaleBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleBlock.prototype, "factor", {
/**
* Gets the factor input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ScaleBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ScaleBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = " + this.input.associatedVariableName + " * " + this.factor.associatedVariableName + ";\r\n");
return this;
};
return ScaleBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ScaleBlock"] = ScaleBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/simplexPerlin3DBlock.ts":
/*!*******************************************************!*\
!*** ./Materials/Node/Blocks/simplexPerlin3DBlock.ts ***!
\*******************************************************/
/*! exports provided: SimplexPerlin3DBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SimplexPerlin3DBlock", function() { return SimplexPerlin3DBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* block used to Generate a Simplex Perlin 3d Noise Pattern
*/
//
// Wombat
// An efficient texture-free GLSL procedural noise library
// Source: https://github.com/BrianSharpe/Wombat
// Derived from: https://github.com/BrianSharpe/GPU-Noise-Lib
//
// I'm not one for copyrights. Use the code however you wish.
// All I ask is that credit be given back to the blog or myself when appropriate.
// And also to let me know if you come up with any changes, improvements, thoughts or interesting uses for this stuff. :)
// Thanks!
//
// Brian Sharpe
// brisharpe CIRCLE_A yahoo DOT com
// http://briansharpe.wordpress.com
// https://github.com/BrianSharpe
//
//
// This is a modified version of Stefan Gustavson's and Ian McEwan's work at http://github.com/ashima/webgl-noise
// Modifications are...
// - faster random number generation
// - analytical final normalization
// - space scaled can have an approx feature size of 1.0
// - filter kernel changed to fix discontinuities at tetrahedron boundaries
//
// Converted to BJS by Pryme8
//
// Simplex Perlin Noise 3D
// Return value range of -1.0->1.0
//
var SimplexPerlin3DBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SimplexPerlin3DBlock, _super);
/**
* Creates a new SimplexPerlin3DBlock
* @param name defines the block name
*/
function SimplexPerlin3DBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("seed", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
SimplexPerlin3DBlock.prototype.getClassName = function () {
return "SimplexPerlin3DBlock";
};
Object.defineProperty(SimplexPerlin3DBlock.prototype, "seed", {
/**
* Gets the seed operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SimplexPerlin3DBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
SimplexPerlin3DBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (!this.seed.isConnected) {
return;
}
if (!this._outputs[0].hasEndpoints) {
return;
}
var functionString = "const float SKEWFACTOR = 1.0/3.0;\r\n";
functionString += "const float UNSKEWFACTOR = 1.0/6.0;\r\n";
functionString += "const float SIMPLEX_CORNER_POS = 0.5;\r\n";
functionString += "const float SIMPLEX_TETRAHADRON_HEIGHT = 0.70710678118654752440084436210485;\r\n";
functionString += "float SimplexPerlin3D( vec3 P ){\r\n";
functionString += " P *= SIMPLEX_TETRAHADRON_HEIGHT;\r\n";
functionString += " vec3 Pi = floor( P + dot( P, vec3( SKEWFACTOR) ) );";
functionString += " vec3 x0 = P - Pi + dot(Pi, vec3( UNSKEWFACTOR ) );\r\n";
functionString += " vec3 g = step(x0.yzx, x0.xyz);\r\n";
functionString += " vec3 l = 1.0 - g;\r\n";
functionString += " vec3 Pi_1 = min( g.xyz, l.zxy );\r\n";
functionString += " vec3 Pi_2 = max( g.xyz, l.zxy );\r\n";
functionString += " vec3 x1 = x0 - Pi_1 + UNSKEWFACTOR;\r\n";
functionString += " vec3 x2 = x0 - Pi_2 + SKEWFACTOR;\r\n";
functionString += " vec3 x3 = x0 - SIMPLEX_CORNER_POS;\r\n";
functionString += " vec4 v1234_x = vec4( x0.x, x1.x, x2.x, x3.x );\r\n";
functionString += " vec4 v1234_y = vec4( x0.y, x1.y, x2.y, x3.y );\r\n";
functionString += " vec4 v1234_z = vec4( x0.z, x1.z, x2.z, x3.z );\r\n";
functionString += " Pi.xyz = Pi.xyz - floor(Pi.xyz * ( 1.0 / 69.0 )) * 69.0;\r\n";
functionString += " vec3 Pi_inc1 = step( Pi, vec3( 69.0 - 1.5 ) ) * ( Pi + 1.0 );\r\n";
functionString += " vec4 Pt = vec4( Pi.xy, Pi_inc1.xy ) + vec2( 50.0, 161.0 ).xyxy;\r\n";
functionString += " Pt *= Pt;\r\n";
functionString += " vec4 V1xy_V2xy = mix( Pt.xyxy, Pt.zwzw, vec4( Pi_1.xy, Pi_2.xy ) );\r\n";
functionString += " Pt = vec4( Pt.x, V1xy_V2xy.xz, Pt.z ) * vec4( Pt.y, V1xy_V2xy.yw, Pt.w );\r\n";
functionString += " const vec3 SOMELARGEFLOATS = vec3( 635.298681, 682.357502, 668.926525 );\r\n";
functionString += " const vec3 ZINC = vec3( 48.500388, 65.294118, 63.934599 );\r\n";
functionString += " vec3 lowz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi.zzz * ZINC.xyz ) );\r\n";
functionString += " vec3 highz_mods = vec3( 1.0 / ( SOMELARGEFLOATS.xyz + Pi_inc1.zzz * ZINC.xyz ) );\r\n";
functionString += " Pi_1 = ( Pi_1.z < 0.5 ) ? lowz_mods : highz_mods;\r\n";
functionString += " Pi_2 = ( Pi_2.z < 0.5 ) ? lowz_mods : highz_mods;\r\n";
functionString += " vec4 hash_0 = fract( Pt * vec4( lowz_mods.x, Pi_1.x, Pi_2.x, highz_mods.x ) ) - 0.49999;\r\n";
functionString += " vec4 hash_1 = fract( Pt * vec4( lowz_mods.y, Pi_1.y, Pi_2.y, highz_mods.y ) ) - 0.49999;\r\n";
functionString += " vec4 hash_2 = fract( Pt * vec4( lowz_mods.z, Pi_1.z, Pi_2.z, highz_mods.z ) ) - 0.49999;\r\n";
functionString += " vec4 grad_results = inversesqrt( hash_0 * hash_0 + hash_1 * hash_1 + hash_2 * hash_2 ) * ( hash_0 * v1234_x + hash_1 * v1234_y + hash_2 * v1234_z );\r\n";
functionString += " const float FINAL_NORMALIZATION = 37.837227241611314102871574478976;\r\n";
functionString += " vec4 kernel_weights = v1234_x * v1234_x + v1234_y * v1234_y + v1234_z * v1234_z;\r\n";
functionString += " kernel_weights = max(0.5 - kernel_weights, 0.0);\r\n";
functionString += " kernel_weights = kernel_weights*kernel_weights*kernel_weights;\r\n";
functionString += " return dot( kernel_weights, grad_results ) * FINAL_NORMALIZATION;\r\n";
functionString += "}\r\n";
state._emitFunction('SimplexPerlin3D', functionString, '// SimplexPerlin3D');
state.compilationString += this._declareOutput(this._outputs[0], state) + (" = SimplexPerlin3D(" + this.seed.associatedVariableName + ");\r\n");
return this;
};
return SimplexPerlin3DBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.SimplexPerlin3DBlock"] = SimplexPerlin3DBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/smoothStepBlock.ts":
/*!**************************************************!*\
!*** ./Materials/Node/Blocks/smoothStepBlock.ts ***!
\**************************************************/
/*! exports provided: SmoothStepBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SmoothStepBlock", function() { return SmoothStepBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to smooth step a value
*/
var SmoothStepBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SmoothStepBlock, _super);
/**
* Creates a new SmoothStepBlock
* @param name defines the block name
*/
function SmoothStepBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerInput("edge0", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerInput("edge1", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
SmoothStepBlock.prototype.getClassName = function () {
return "SmoothStepBlock";
};
Object.defineProperty(SmoothStepBlock.prototype, "value", {
/**
* Gets the value operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SmoothStepBlock.prototype, "edge0", {
/**
* Gets the first edge operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SmoothStepBlock.prototype, "edge1", {
/**
* Gets the second edge operand input component
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SmoothStepBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
SmoothStepBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = smoothstep(" + this.edge0.associatedVariableName + ", " + this.edge1.associatedVariableName + ", " + this.value.associatedVariableName + ");\r\n");
return this;
};
return SmoothStepBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.SmoothStepBlock"] = SmoothStepBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/stepBlock.ts":
/*!********************************************!*\
!*** ./Materials/Node/Blocks/stepBlock.ts ***!
\********************************************/
/*! exports provided: StepBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StepBlock", function() { return StepBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to step a value
*/
var StepBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StepBlock, _super);
/**
* Creates a new StepBlock
* @param name defines the block name
*/
function StepBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("value", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerInput("edge", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
StepBlock.prototype.getClassName = function () {
return "StepBlock";
};
Object.defineProperty(StepBlock.prototype, "value", {
/**
* Gets the value operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(StepBlock.prototype, "edge", {
/**
* Gets the edge operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(StepBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
StepBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = step(" + this.edge.associatedVariableName + ", " + this.value.associatedVariableName + ");\r\n");
return this;
};
return StepBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.StepBlock"] = StepBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/subtractBlock.ts":
/*!************************************************!*\
!*** ./Materials/Node/Blocks/subtractBlock.ts ***!
\************************************************/
/*! exports provided: SubtractBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtractBlock", function() { return SubtractBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to subtract 2 vectors
*/
var SubtractBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SubtractBlock, _super);
/**
* Creates a new SubtractBlock
* @param name defines the block name
*/
function SubtractBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("left", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("right", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._linkConnectionTypes(0, 1);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
SubtractBlock.prototype.getClassName = function () {
return "SubtractBlock";
};
Object.defineProperty(SubtractBlock.prototype, "left", {
/**
* Gets the left operand input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubtractBlock.prototype, "right", {
/**
* Gets the right operand input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(SubtractBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
SubtractBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = " + this.left.associatedVariableName + " - " + this.right.associatedVariableName + ";\r\n");
return this;
};
return SubtractBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.SubtractBlock"] = SubtractBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/transformBlock.ts":
/*!*************************************************!*\
!*** ./Materials/Node/Blocks/transformBlock.ts ***!
\*************************************************/
/*! exports provided: TransformBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransformBlock", function() { return TransformBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to transform a vector (2, 3 or 4) with a matrix. It will generate a Vector4
*/
var TransformBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TransformBlock, _super);
/**
* Creates a new TransformBlock
* @param name defines the block name
*/
function TransformBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Vertex) || this;
/**
* Defines the value to use to complement W value to transform it to a Vector4
*/
_this.complementW = 1;
/**
* Defines the value to use to complement z value to transform it to a Vector4
*/
_this.complementZ = 0;
_this.registerInput("vector", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerInput("transform", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerOutput("xyz", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this._inputs[0].onConnectionObservable.add(function (other) {
if (other.ownerBlock.isInput) {
var otherAsInput = other.ownerBlock;
if (otherAsInput.name === "normal" || otherAsInput.name === "tangent") {
_this.complementW = 0;
}
}
});
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
TransformBlock.prototype.getClassName = function () {
return "TransformBlock";
};
Object.defineProperty(TransformBlock.prototype, "vector", {
/**
* Gets the vector input
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TransformBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TransformBlock.prototype, "xyz", {
/**
* Gets the xyz output component
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TransformBlock.prototype, "transform", {
/**
* Gets the matrix transform input
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
TransformBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var vector = this.vector;
var transform = this.transform;
if (vector.connectedPoint) {
// None uniform scaling case.
if (this.complementW === 0) {
var comments = "//" + this.name;
state._emitFunctionFromInclude("helperFunctions", comments);
state.sharedData.blocksWithDefines.push(this);
var transformName = state._getFreeVariableName(transform.associatedVariableName + "_NUS");
state.compilationString += "mat3 " + transformName + " = mat3(" + transform.associatedVariableName + ");\r\n";
state.compilationString += "#ifdef NONUNIFORMSCALING\r\n";
state.compilationString += transformName + " = transposeMat3(inverseMat3(" + transformName + "));\r\n";
state.compilationString += "#endif\r\n";
switch (vector.connectedPoint.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2:
state.compilationString += this._declareOutput(this.output, state) + (" = vec4(" + transformName + " * vec3(" + vector.associatedVariableName + ", " + this._writeFloat(this.complementZ) + "), " + this._writeFloat(this.complementW) + ");\r\n");
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3:
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3:
state.compilationString += this._declareOutput(this.output, state) + (" = vec4(" + transformName + " * " + vector.associatedVariableName + ", " + this._writeFloat(this.complementW) + ");\r\n");
break;
default:
state.compilationString += this._declareOutput(this.output, state) + (" = vec4(" + transformName + " * " + vector.associatedVariableName + ".xyz, " + this._writeFloat(this.complementW) + ");\r\n");
break;
}
}
else {
var transformName = transform.associatedVariableName;
switch (vector.connectedPoint.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2:
state.compilationString += this._declareOutput(this.output, state) + (" = " + transformName + " * vec4(" + vector.associatedVariableName + ", " + this._writeFloat(this.complementZ) + ", " + this._writeFloat(this.complementW) + ");\r\n");
break;
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3:
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Color3:
state.compilationString += this._declareOutput(this.output, state) + (" = " + transformName + " * vec4(" + vector.associatedVariableName + ", " + this._writeFloat(this.complementW) + ");\r\n");
break;
default:
state.compilationString += this._declareOutput(this.output, state) + (" = " + transformName + " * " + vector.associatedVariableName + ";\r\n");
break;
}
}
if (this.xyz.hasEndpoints) {
state.compilationString += this._declareOutput(this.xyz, state) + (" = " + this.output.associatedVariableName + ".xyz;\r\n");
}
}
return this;
};
/**
* Update defines for shader compilation
* @param mesh defines the mesh to be rendered
* @param nodeMaterial defines the node material requesting the update
* @param defines defines the material defines to update
* @param useInstances specifies that instances should be used
* @param subMesh defines which submesh to render
*/
TransformBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines, useInstances, subMesh) {
if (useInstances === void 0) { useInstances = false; }
// Do nothing
if (mesh.nonUniformScaling) {
defines.setValue("NONUNIFORMSCALING", true);
}
};
TransformBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.complementZ = this.complementZ;
serializationObject.complementW = this.complementW;
return serializationObject;
};
TransformBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.complementZ = serializationObject.complementZ !== undefined ? serializationObject.complementZ : 0.0;
this.complementW = serializationObject.complementW !== undefined ? serializationObject.complementW : 1.0;
};
TransformBlock.prototype._dumpPropertiesCode = function () {
var codeString = this._codeVariableName + ".complementZ = " + this.complementZ + ";\r\n";
codeString += this._codeVariableName + ".complementW = " + this.complementW + ";\r\n";
return codeString;
};
return TransformBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.TransformBlock"] = TransformBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/trigonometryBlock.ts":
/*!****************************************************!*\
!*** ./Materials/Node/Blocks/trigonometryBlock.ts ***!
\****************************************************/
/*! exports provided: TrigonometryBlockOperations, TrigonometryBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlockOperations", function() { return TrigonometryBlockOperations; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlock", function() { return TrigonometryBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Operations supported by the Trigonometry block
*/
var TrigonometryBlockOperations;
(function (TrigonometryBlockOperations) {
/** Cos */
TrigonometryBlockOperations[TrigonometryBlockOperations["Cos"] = 0] = "Cos";
/** Sin */
TrigonometryBlockOperations[TrigonometryBlockOperations["Sin"] = 1] = "Sin";
/** Abs */
TrigonometryBlockOperations[TrigonometryBlockOperations["Abs"] = 2] = "Abs";
/** Exp */
TrigonometryBlockOperations[TrigonometryBlockOperations["Exp"] = 3] = "Exp";
/** Exp2 */
TrigonometryBlockOperations[TrigonometryBlockOperations["Exp2"] = 4] = "Exp2";
/** Round */
TrigonometryBlockOperations[TrigonometryBlockOperations["Round"] = 5] = "Round";
/** Floor */
TrigonometryBlockOperations[TrigonometryBlockOperations["Floor"] = 6] = "Floor";
/** Ceiling */
TrigonometryBlockOperations[TrigonometryBlockOperations["Ceiling"] = 7] = "Ceiling";
/** Square root */
TrigonometryBlockOperations[TrigonometryBlockOperations["Sqrt"] = 8] = "Sqrt";
/** Log */
TrigonometryBlockOperations[TrigonometryBlockOperations["Log"] = 9] = "Log";
/** Tangent */
TrigonometryBlockOperations[TrigonometryBlockOperations["Tan"] = 10] = "Tan";
/** Arc tangent */
TrigonometryBlockOperations[TrigonometryBlockOperations["ArcTan"] = 11] = "ArcTan";
/** Arc cosinus */
TrigonometryBlockOperations[TrigonometryBlockOperations["ArcCos"] = 12] = "ArcCos";
/** Arc sinus */
TrigonometryBlockOperations[TrigonometryBlockOperations["ArcSin"] = 13] = "ArcSin";
/** Fraction */
TrigonometryBlockOperations[TrigonometryBlockOperations["Fract"] = 14] = "Fract";
/** Sign */
TrigonometryBlockOperations[TrigonometryBlockOperations["Sign"] = 15] = "Sign";
/** To radians (from degrees) */
TrigonometryBlockOperations[TrigonometryBlockOperations["Radians"] = 16] = "Radians";
/** To degrees (from radians) */
TrigonometryBlockOperations[TrigonometryBlockOperations["Degrees"] = 17] = "Degrees";
})(TrigonometryBlockOperations || (TrigonometryBlockOperations = {}));
/**
* Block used to apply trigonometry operation to floats
*/
var TrigonometryBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TrigonometryBlock, _super);
/**
* Creates a new TrigonometryBlock
* @param name defines the block name
*/
function TrigonometryBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
/**
* Gets or sets the operation applied by the block
*/
_this.operation = TrigonometryBlockOperations.Cos;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
TrigonometryBlock.prototype.getClassName = function () {
return "TrigonometryBlock";
};
Object.defineProperty(TrigonometryBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(TrigonometryBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
TrigonometryBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
var operation = "";
switch (this.operation) {
case TrigonometryBlockOperations.Cos: {
operation = "cos";
break;
}
case TrigonometryBlockOperations.Sin: {
operation = "sin";
break;
}
case TrigonometryBlockOperations.Abs: {
operation = "abs";
break;
}
case TrigonometryBlockOperations.Exp: {
operation = "exp";
break;
}
case TrigonometryBlockOperations.Exp2: {
operation = "exp2";
break;
}
case TrigonometryBlockOperations.Round: {
operation = "round";
break;
}
case TrigonometryBlockOperations.Floor: {
operation = "floor";
break;
}
case TrigonometryBlockOperations.Ceiling: {
operation = "ceil";
break;
}
case TrigonometryBlockOperations.Sqrt: {
operation = "sqrt";
break;
}
case TrigonometryBlockOperations.Log: {
operation = "log";
break;
}
case TrigonometryBlockOperations.Tan: {
operation = "tan";
break;
}
case TrigonometryBlockOperations.ArcTan: {
operation = "atan";
break;
}
case TrigonometryBlockOperations.ArcCos: {
operation = "acos";
break;
}
case TrigonometryBlockOperations.ArcSin: {
operation = "asin";
break;
}
case TrigonometryBlockOperations.Fract: {
operation = "fract";
break;
}
case TrigonometryBlockOperations.Sign: {
operation = "sign";
break;
}
case TrigonometryBlockOperations.Radians: {
operation = "radians";
break;
}
case TrigonometryBlockOperations.Degrees: {
operation = "degrees";
break;
}
}
state.compilationString += this._declareOutput(output, state) + (" = " + operation + "(" + this.input.associatedVariableName + ");\r\n");
return this;
};
TrigonometryBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.operation = this.operation;
return serializationObject;
};
TrigonometryBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.operation = serializationObject.operation;
};
TrigonometryBlock.prototype._dumpPropertiesCode = function () {
var codeString = this._codeVariableName + ".operation = BABYLON.TrigonometryBlockOperations." + TrigonometryBlockOperations[this.operation] + ";\r\n";
return codeString;
};
return TrigonometryBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.TrigonometryBlock"] = TrigonometryBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/vectorMergerBlock.ts":
/*!****************************************************!*\
!*** ./Materials/Node/Blocks/vectorMergerBlock.ts ***!
\****************************************************/
/*! exports provided: VectorMergerBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VectorMergerBlock", function() { return VectorMergerBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to create a Vector2/3/4 out of individual inputs (one for each component)
*/
var VectorMergerBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VectorMergerBlock, _super);
/**
* Create a new VectorMergerBlock
* @param name defines the block name
*/
function VectorMergerBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("xyz ", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3, true);
_this.registerInput("xy ", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, true);
_this.registerInput("x", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("y", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("z", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerInput("w", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float, true);
_this.registerOutput("xyzw", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerOutput("xyz", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("xy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
VectorMergerBlock.prototype.getClassName = function () {
return "VectorMergerBlock";
};
Object.defineProperty(VectorMergerBlock.prototype, "xyzIn", {
/**
* Gets the xyz component (input)
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "xyIn", {
/**
* Gets the xy component (input)
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "x", {
/**
* Gets the x component (input)
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "y", {
/**
* Gets the y component (input)
*/
get: function () {
return this._inputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "z", {
/**
* Gets the z component (input)
*/
get: function () {
return this._inputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "w", {
/**
* Gets the w component (input)
*/
get: function () {
return this._inputs[5];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "xyzw", {
/**
* Gets the xyzw component (output)
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "xyzOut", {
/**
* Gets the xyz component (output)
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "xyOut", {
/**
* Gets the xy component (output)
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "xy", {
/**
* Gets the xy component (output)
* @deprecated Please use xyOut instead.
*/
get: function () {
return this.xyOut;
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorMergerBlock.prototype, "xyz", {
/**
* Gets the xyz component (output)
* @deprecated Please use xyzOut instead.
*/
get: function () {
return this.xyzOut;
},
enumerable: false,
configurable: true
});
VectorMergerBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var xInput = this.x;
var yInput = this.y;
var zInput = this.z;
var wInput = this.w;
var xyInput = this.xyIn;
var xyzInput = this.xyzIn;
var v4Output = this._outputs[0];
var v3Output = this._outputs[1];
var v2Output = this._outputs[2];
if (xyInput.isConnected) {
if (v4Output.hasEndpoints) {
state.compilationString += this._declareOutput(v4Output, state) + (" = vec4(" + xyInput.associatedVariableName + ", " + (zInput.isConnected ? this._writeVariable(zInput) : "0.0") + ", " + (wInput.isConnected ? this._writeVariable(wInput) : "0.0") + ");\r\n");
}
else if (v3Output.hasEndpoints) {
state.compilationString += this._declareOutput(v3Output, state) + (" = vec3(" + xyInput.associatedVariableName + ", " + (zInput.isConnected ? this._writeVariable(zInput) : "0.0") + ");\r\n");
}
else if (v2Output.hasEndpoints) {
state.compilationString += this._declareOutput(v2Output, state) + (" = " + xyInput.associatedVariableName + ";\r\n");
}
}
else if (xyzInput.isConnected) {
if (v4Output.hasEndpoints) {
state.compilationString += this._declareOutput(v4Output, state) + (" = vec4(" + xyzInput.associatedVariableName + ", " + (wInput.isConnected ? this._writeVariable(wInput) : "0.0") + ");\r\n");
}
else if (v3Output.hasEndpoints) {
state.compilationString += this._declareOutput(v3Output, state) + (" = " + xyzInput.associatedVariableName + ";\r\n");
}
else if (v2Output.hasEndpoints) {
state.compilationString += this._declareOutput(v2Output, state) + (" = " + xyzInput.associatedVariableName + ".xy;\r\n");
}
}
else {
if (v4Output.hasEndpoints) {
state.compilationString += this._declareOutput(v4Output, state) + (" = vec4(" + (xInput.isConnected ? this._writeVariable(xInput) : "0.0") + ", " + (yInput.isConnected ? this._writeVariable(yInput) : "0.0") + ", " + (zInput.isConnected ? this._writeVariable(zInput) : "0.0") + ", " + (wInput.isConnected ? this._writeVariable(wInput) : "0.0") + ");\r\n");
}
else if (v3Output.hasEndpoints) {
state.compilationString += this._declareOutput(v3Output, state) + (" = vec3(" + (xInput.isConnected ? this._writeVariable(xInput) : "0.0") + ", " + (yInput.isConnected ? this._writeVariable(yInput) : "0.0") + ", " + (zInput.isConnected ? this._writeVariable(zInput) : "0.0") + ");\r\n");
}
else if (v2Output.hasEndpoints) {
state.compilationString += this._declareOutput(v2Output, state) + (" = vec2(" + (xInput.isConnected ? this._writeVariable(xInput) : "0.0") + ", " + (yInput.isConnected ? this._writeVariable(yInput) : "0.0") + ");\r\n");
}
}
return this;
};
return VectorMergerBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.VectorMergerBlock"] = VectorMergerBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/vectorSplitterBlock.ts":
/*!******************************************************!*\
!*** ./Materials/Node/Blocks/vectorSplitterBlock.ts ***!
\******************************************************/
/*! exports provided: VectorSplitterBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VectorSplitterBlock", function() { return VectorSplitterBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Block used to expand a Vector3/4 into 4 outputs (one for each component)
*/
var VectorSplitterBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VectorSplitterBlock, _super);
/**
* Create a new VectorSplitterBlock
* @param name defines the block name
*/
function VectorSplitterBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("xyzw", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4, true);
_this.registerInput("xyz ", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3, true);
_this.registerInput("xy ", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2, true);
_this.registerOutput("xyz", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("xy", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
_this.registerOutput("x", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("y", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("z", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("w", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.inputsAreExclusive = true;
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
VectorSplitterBlock.prototype.getClassName = function () {
return "VectorSplitterBlock";
};
Object.defineProperty(VectorSplitterBlock.prototype, "xyzw", {
/**
* Gets the xyzw component (input)
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "xyzIn", {
/**
* Gets the xyz component (input)
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "xyIn", {
/**
* Gets the xy component (input)
*/
get: function () {
return this._inputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "xyzOut", {
/**
* Gets the xyz component (output)
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "xyOut", {
/**
* Gets the xy component (output)
*/
get: function () {
return this._outputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "x", {
/**
* Gets the x component (output)
*/
get: function () {
return this._outputs[2];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "y", {
/**
* Gets the y component (output)
*/
get: function () {
return this._outputs[3];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "z", {
/**
* Gets the z component (output)
*/
get: function () {
return this._outputs[4];
},
enumerable: false,
configurable: true
});
Object.defineProperty(VectorSplitterBlock.prototype, "w", {
/**
* Gets the w component (output)
*/
get: function () {
return this._outputs[5];
},
enumerable: false,
configurable: true
});
VectorSplitterBlock.prototype._inputRename = function (name) {
switch (name) {
case "xy ":
return "xyIn";
case "xyz ":
return "xyzIn";
default:
return name;
}
};
VectorSplitterBlock.prototype._outputRename = function (name) {
switch (name) {
case "xy":
return "xyOut";
case "xyz":
return "xyzOut";
default:
return name;
}
};
VectorSplitterBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var input = this.xyzw.isConnected ? this.xyzw : this.xyzIn.isConnected ? this.xyzIn : this.xyIn;
var xyzOutput = this._outputs[0];
var xyOutput = this._outputs[1];
var xOutput = this._outputs[2];
var yOutput = this._outputs[3];
var zOutput = this._outputs[4];
var wOutput = this._outputs[5];
if (xyzOutput.hasEndpoints) {
if (input === this.xyIn) {
state.compilationString += this._declareOutput(xyzOutput, state) + (" = vec3(" + input.associatedVariableName + ", 0.0);\r\n");
}
else {
state.compilationString += this._declareOutput(xyzOutput, state) + (" = " + input.associatedVariableName + ".xyz;\r\n");
}
}
if (xyOutput.hasEndpoints) {
state.compilationString += this._declareOutput(xyOutput, state) + (" = " + input.associatedVariableName + ".xy;\r\n");
}
if (xOutput.hasEndpoints) {
state.compilationString += this._declareOutput(xOutput, state) + (" = " + input.associatedVariableName + ".x;\r\n");
}
if (yOutput.hasEndpoints) {
state.compilationString += this._declareOutput(yOutput, state) + (" = " + input.associatedVariableName + ".y;\r\n");
}
if (zOutput.hasEndpoints) {
state.compilationString += this._declareOutput(zOutput, state) + (" = " + input.associatedVariableName + ".z;\r\n");
}
if (wOutput.hasEndpoints) {
state.compilationString += this._declareOutput(wOutput, state) + (" = " + input.associatedVariableName + ".w;\r\n");
}
return this;
};
return VectorSplitterBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.VectorSplitterBlock"] = VectorSplitterBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/viewDirectionBlock.ts":
/*!*****************************************************!*\
!*** ./Materials/Node/Blocks/viewDirectionBlock.ts ***!
\*****************************************************/
/*! exports provided: ViewDirectionBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewDirectionBlock", function() { return ViewDirectionBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../Enums/nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony import */ var _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/**
* Block used to get the view direction
*/
var ViewDirectionBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ViewDirectionBlock, _super);
/**
* Creates a new ViewDirectionBlock
* @param name defines the block name
*/
function ViewDirectionBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
_this.registerInput("worldPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector4);
_this.registerInput("cameraPosition", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
ViewDirectionBlock.prototype.getClassName = function () {
return "ViewDirectionBlock";
};
Object.defineProperty(ViewDirectionBlock.prototype, "worldPosition", {
/**
* Gets the world position component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ViewDirectionBlock.prototype, "cameraPosition", {
/**
* Gets the camera position component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(ViewDirectionBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
ViewDirectionBlock.prototype.autoConfigure = function (material) {
if (!this.cameraPosition.isConnected) {
var cameraPositionInput = material.getInputBlockByPredicate(function (b) { return b.systemValue === _Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].CameraPosition; });
if (!cameraPositionInput) {
cameraPositionInput = new _Input_inputBlock__WEBPACK_IMPORTED_MODULE_6__["InputBlock"]("cameraPosition");
cameraPositionInput.setAsSystemValue(_Enums_nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialSystemValues"].CameraPosition);
}
cameraPositionInput.output.connectTo(this.cameraPosition);
}
};
ViewDirectionBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
state.compilationString += this._declareOutput(output, state) + (" = normalize(" + this.cameraPosition.associatedVariableName + " - " + this.worldPosition.associatedVariableName + ".xyz);\r\n");
return this;
};
return ViewDirectionBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.ViewDirectionBlock"] = ViewDirectionBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/waveBlock.ts":
/*!********************************************!*\
!*** ./Materials/Node/Blocks/waveBlock.ts ***!
\********************************************/
/*! exports provided: WaveBlockKind, WaveBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WaveBlockKind", function() { return WaveBlockKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WaveBlock", function() { return WaveBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Operations supported by the Wave block
*/
var WaveBlockKind;
(function (WaveBlockKind) {
/** SawTooth */
WaveBlockKind[WaveBlockKind["SawTooth"] = 0] = "SawTooth";
/** Square */
WaveBlockKind[WaveBlockKind["Square"] = 1] = "Square";
/** Triangle */
WaveBlockKind[WaveBlockKind["Triangle"] = 2] = "Triangle";
})(WaveBlockKind || (WaveBlockKind = {}));
/**
* Block used to apply wave operation to floats
*/
var WaveBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WaveBlock, _super);
/**
* Creates a new WaveBlock
* @param name defines the block name
*/
function WaveBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
/**
* Gets or sets the kibnd of wave to be applied by the block
*/
_this.kind = WaveBlockKind.SawTooth;
_this.registerInput("input", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].AutoDetect);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput);
_this._outputs[0]._typeConnectionSource = _this._inputs[0];
_this._inputs[0].excludedConnectionPointTypes.push(_Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Matrix);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
WaveBlock.prototype.getClassName = function () {
return "WaveBlock";
};
Object.defineProperty(WaveBlock.prototype, "input", {
/**
* Gets the input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(WaveBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
WaveBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
var output = this._outputs[0];
switch (this.kind) {
case WaveBlockKind.SawTooth: {
state.compilationString += this._declareOutput(output, state) + (" = " + this.input.associatedVariableName + " - floor(0.5 + " + this.input.associatedVariableName + ");\r\n");
break;
}
case WaveBlockKind.Square: {
state.compilationString += this._declareOutput(output, state) + (" = 1.0 - 2.0 * round(fract(" + this.input.associatedVariableName + "));\r\n");
break;
}
case WaveBlockKind.Triangle: {
state.compilationString += this._declareOutput(output, state) + (" = 2.0 * abs(2.0 * (" + this.input.associatedVariableName + " - floor(0.5 + " + this.input.associatedVariableName + "))) - 1.0;\r\n");
break;
}
}
return this;
};
WaveBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.kind = this.kind;
return serializationObject;
};
WaveBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.kind = serializationObject.kind;
};
return WaveBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.WaveBlock"] = WaveBlock;
/***/ }),
/***/ "./Materials/Node/Blocks/worleyNoise3DBlock.ts":
/*!*****************************************************!*\
!*** ./Materials/Node/Blocks/worleyNoise3DBlock.ts ***!
\*****************************************************/
/*! exports provided: WorleyNoise3DBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WorleyNoise3DBlock", function() { return WorleyNoise3DBlock; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/**
* block used to Generate a Worley Noise 3D Noise Pattern
*/
// Source: https://github.com/Erkaman/glsl-worley
// Converted to BJS by Pryme8
//
// Worley Noise 3D
// Return vec2 value range of -1.0->1.0, F1-F2 respectivly
var WorleyNoise3DBlock = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WorleyNoise3DBlock, _super);
/**
* Creates a new WorleyNoise3DBlock
* @param name defines the block name
*/
function WorleyNoise3DBlock(name) {
var _this = _super.call(this, name, _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialBlockTargets"].Neutral) || this;
/** Gets or sets a boolean indicating that normal should be inverted on X axis */
_this.manhattanDistance = false;
_this.registerInput("seed", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector3);
_this.registerInput("jitter", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Float);
_this.registerOutput("output", _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointTypes"].Vector2);
return _this;
}
/**
* Gets the current class name
* @returns the class name
*/
WorleyNoise3DBlock.prototype.getClassName = function () {
return "WorleyNoise3DBlock";
};
Object.defineProperty(WorleyNoise3DBlock.prototype, "seed", {
/**
* Gets the seed input component
*/
get: function () {
return this._inputs[0];
},
enumerable: false,
configurable: true
});
Object.defineProperty(WorleyNoise3DBlock.prototype, "jitter", {
/**
* Gets the jitter input component
*/
get: function () {
return this._inputs[1];
},
enumerable: false,
configurable: true
});
Object.defineProperty(WorleyNoise3DBlock.prototype, "output", {
/**
* Gets the output component
*/
get: function () {
return this._outputs[0];
},
enumerable: false,
configurable: true
});
WorleyNoise3DBlock.prototype._buildBlock = function (state) {
_super.prototype._buildBlock.call(this, state);
if (!this.seed.isConnected) {
return;
}
if (!this._outputs[0].hasEndpoints) {
return;
}
var functionString = "vec3 permute(vec3 x){\r\n";
functionString += " return mod((34.0 * x + 1.0) * x, 289.0);\r\n";
functionString += "}\r\n\r\n";
functionString += "vec3 dist(vec3 x, vec3 y, vec3 z, bool manhattanDistance){\r\n";
functionString += " return manhattanDistance ? abs(x) + abs(y) + abs(z) : (x * x + y * y + z * z);\r\n";
functionString += "}\r\n\r\n";
functionString += "vec2 worley(vec3 P, float jitter, bool manhattanDistance){\r\n";
functionString += " float K = 0.142857142857; // 1/7\r\n";
functionString += " float Ko = 0.428571428571; // 1/2-K/2\r\n";
functionString += " float K2 = 0.020408163265306; // 1/(7*7)\r\n";
functionString += " float Kz = 0.166666666667; // 1/6\r\n";
functionString += " float Kzo = 0.416666666667; // 1/2-1/6*2\r\n";
functionString += "\r\n";
functionString += " vec3 Pi = mod(floor(P), 289.0);\r\n";
functionString += " vec3 Pf = fract(P) - 0.5;\r\n";
functionString += "\r\n";
functionString += " vec3 Pfx = Pf.x + vec3(1.0, 0.0, -1.0);\r\n";
functionString += " vec3 Pfy = Pf.y + vec3(1.0, 0.0, -1.0);\r\n";
functionString += " vec3 Pfz = Pf.z + vec3(1.0, 0.0, -1.0);\r\n";
functionString += "\r\n";
functionString += " vec3 p = permute(Pi.x + vec3(-1.0, 0.0, 1.0));\r\n";
functionString += " vec3 p1 = permute(p + Pi.y - 1.0);\r\n";
functionString += " vec3 p2 = permute(p + Pi.y);\r\n";
functionString += " vec3 p3 = permute(p + Pi.y + 1.0);\r\n";
functionString += "\r\n";
functionString += " vec3 p11 = permute(p1 + Pi.z - 1.0);\r\n";
functionString += " vec3 p12 = permute(p1 + Pi.z);\r\n";
functionString += " vec3 p13 = permute(p1 + Pi.z + 1.0);\r\n";
functionString += "\r\n";
functionString += " vec3 p21 = permute(p2 + Pi.z - 1.0);\r\n";
functionString += " vec3 p22 = permute(p2 + Pi.z);\r\n";
functionString += " vec3 p23 = permute(p2 + Pi.z + 1.0);\r\n";
functionString += "\r\n";
functionString += " vec3 p31 = permute(p3 + Pi.z - 1.0);\r\n";
functionString += " vec3 p32 = permute(p3 + Pi.z);\r\n";
functionString += " vec3 p33 = permute(p3 + Pi.z + 1.0);\r\n";
functionString += "\r\n";
functionString += " vec3 ox11 = fract(p11*K) - Ko;\r\n";
functionString += " vec3 oy11 = mod(floor(p11*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz11 = floor(p11*K2)*Kz - Kzo; // p11 < 289 guaranteed\r\n";
functionString += "\r\n";
functionString += " vec3 ox12 = fract(p12*K) - Ko;\r\n";
functionString += " vec3 oy12 = mod(floor(p12*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz12 = floor(p12*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox13 = fract(p13*K) - Ko;\r\n";
functionString += " vec3 oy13 = mod(floor(p13*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz13 = floor(p13*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox21 = fract(p21*K) - Ko;\r\n";
functionString += " vec3 oy21 = mod(floor(p21*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz21 = floor(p21*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox22 = fract(p22*K) - Ko;\r\n";
functionString += " vec3 oy22 = mod(floor(p22*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz22 = floor(p22*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox23 = fract(p23*K) - Ko;\r\n";
functionString += " vec3 oy23 = mod(floor(p23*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz23 = floor(p23*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox31 = fract(p31*K) - Ko;\r\n";
functionString += " vec3 oy31 = mod(floor(p31*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz31 = floor(p31*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox32 = fract(p32*K) - Ko;\r\n";
functionString += " vec3 oy32 = mod(floor(p32*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz32 = floor(p32*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 ox33 = fract(p33*K) - Ko;\r\n";
functionString += " vec3 oy33 = mod(floor(p33*K), 7.0)*K - Ko;\r\n";
functionString += " vec3 oz33 = floor(p33*K2)*Kz - Kzo;\r\n";
functionString += "\r\n";
functionString += " vec3 dx11 = Pfx + jitter*ox11;\r\n";
functionString += " vec3 dy11 = Pfy.x + jitter*oy11;\r\n";
functionString += " vec3 dz11 = Pfz.x + jitter*oz11;\r\n";
functionString += "\r\n";
functionString += " vec3 dx12 = Pfx + jitter*ox12;\r\n";
functionString += " vec3 dy12 = Pfy.x + jitter*oy12;\r\n";
functionString += " vec3 dz12 = Pfz.y + jitter*oz12;\r\n";
functionString += "\r\n";
functionString += " vec3 dx13 = Pfx + jitter*ox13;\r\n";
functionString += " vec3 dy13 = Pfy.x + jitter*oy13;\r\n";
functionString += " vec3 dz13 = Pfz.z + jitter*oz13;\r\n";
functionString += "\r\n";
functionString += " vec3 dx21 = Pfx + jitter*ox21;\r\n";
functionString += " vec3 dy21 = Pfy.y + jitter*oy21;\r\n";
functionString += " vec3 dz21 = Pfz.x + jitter*oz21;\r\n";
functionString += "\r\n";
functionString += " vec3 dx22 = Pfx + jitter*ox22;\r\n";
functionString += " vec3 dy22 = Pfy.y + jitter*oy22;\r\n";
functionString += " vec3 dz22 = Pfz.y + jitter*oz22;\r\n";
functionString += "\r\n";
functionString += " vec3 dx23 = Pfx + jitter*ox23;\r\n";
functionString += " vec3 dy23 = Pfy.y + jitter*oy23;\r\n";
functionString += " vec3 dz23 = Pfz.z + jitter*oz23;\r\n";
functionString += "\r\n";
functionString += " vec3 dx31 = Pfx + jitter*ox31;\r\n";
functionString += " vec3 dy31 = Pfy.z + jitter*oy31;\r\n";
functionString += " vec3 dz31 = Pfz.x + jitter*oz31;\r\n";
functionString += "\r\n";
functionString += " vec3 dx32 = Pfx + jitter*ox32;\r\n";
functionString += " vec3 dy32 = Pfy.z + jitter*oy32;\r\n";
functionString += " vec3 dz32 = Pfz.y + jitter*oz32;\r\n";
functionString += "\r\n";
functionString += " vec3 dx33 = Pfx + jitter*ox33;\r\n";
functionString += " vec3 dy33 = Pfy.z + jitter*oy33;\r\n";
functionString += " vec3 dz33 = Pfz.z + jitter*oz33;\r\n";
functionString += "\r\n";
functionString += " vec3 d11 = dist(dx11, dy11, dz11, manhattanDistance);\r\n";
functionString += " vec3 d12 =dist(dx12, dy12, dz12, manhattanDistance);\r\n";
functionString += " vec3 d13 = dist(dx13, dy13, dz13, manhattanDistance);\r\n";
functionString += " vec3 d21 = dist(dx21, dy21, dz21, manhattanDistance);\r\n";
functionString += " vec3 d22 = dist(dx22, dy22, dz22, manhattanDistance);\r\n";
functionString += " vec3 d23 = dist(dx23, dy23, dz23, manhattanDistance);\r\n";
functionString += " vec3 d31 = dist(dx31, dy31, dz31, manhattanDistance);\r\n";
functionString += " vec3 d32 = dist(dx32, dy32, dz32, manhattanDistance);\r\n";
functionString += " vec3 d33 = dist(dx33, dy33, dz33, manhattanDistance);\r\n";
functionString += "\r\n";
functionString += " vec3 d1a = min(d11, d12);\r\n";
functionString += " d12 = max(d11, d12);\r\n";
functionString += " d11 = min(d1a, d13); // Smallest now not in d12 or d13\r\n";
functionString += " d13 = max(d1a, d13);\r\n";
functionString += " d12 = min(d12, d13); // 2nd smallest now not in d13\r\n";
functionString += " vec3 d2a = min(d21, d22);\r\n";
functionString += " d22 = max(d21, d22);\r\n";
functionString += " d21 = min(d2a, d23); // Smallest now not in d22 or d23\r\n";
functionString += " d23 = max(d2a, d23);\r\n";
functionString += " d22 = min(d22, d23); // 2nd smallest now not in d23\r\n";
functionString += " vec3 d3a = min(d31, d32);\r\n";
functionString += " d32 = max(d31, d32);\r\n";
functionString += " d31 = min(d3a, d33); // Smallest now not in d32 or d33\r\n";
functionString += " d33 = max(d3a, d33);\r\n";
functionString += " d32 = min(d32, d33); // 2nd smallest now not in d33\r\n";
functionString += " vec3 da = min(d11, d21);\r\n";
functionString += " d21 = max(d11, d21);\r\n";
functionString += " d11 = min(da, d31); // Smallest now in d11\r\n";
functionString += " d31 = max(da, d31); // 2nd smallest now not in d31\r\n";
functionString += " d11.xy = (d11.x < d11.y) ? d11.xy : d11.yx;\r\n";
functionString += " d11.xz = (d11.x < d11.z) ? d11.xz : d11.zx; // d11.x now smallest\r\n";
functionString += " d12 = min(d12, d21); // 2nd smallest now not in d21\r\n";
functionString += " d12 = min(d12, d22); // nor in d22\r\n";
functionString += " d12 = min(d12, d31); // nor in d31\r\n";
functionString += " d12 = min(d12, d32); // nor in d32\r\n";
functionString += " d11.yz = min(d11.yz,d12.xy); // nor in d12.yz\r\n";
functionString += " d11.y = min(d11.y,d12.z); // Only two more to go\r\n";
functionString += " d11.y = min(d11.y,d11.z); // Done! (Phew!)\r\n";
functionString += " return sqrt(d11.xy); // F1, F2\r\n";
functionString += "}\r\n\r\n";
state._emitFunction('worley3D', functionString, '// Worley3D');
state.compilationString += this._declareOutput(this._outputs[0], state) + (" = worley(" + this.seed.associatedVariableName + ", " + this.jitter.associatedVariableName + ", " + this.manhattanDistance + ");\r\n");
return this;
};
/**
* Exposes the properties to the UI?
*/
WorleyNoise3DBlock.prototype._dumpPropertiesCode = function () {
var codeString = this._codeVariableName + ".manhattanDistance = " + this.manhattanDistance + ";\r\n";
return codeString;
};
/**
* Exposes the properties to the Seralize?
*/
WorleyNoise3DBlock.prototype.serialize = function () {
var serializationObject = _super.prototype.serialize.call(this);
serializationObject.manhattanDistance = this.manhattanDistance;
return serializationObject;
};
/**
* Exposes the properties to the deseralize?
*/
WorleyNoise3DBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
_super.prototype._deserialize.call(this, serializationObject, scene, rootUrl);
this.manhattanDistance = serializationObject.manhattanDistance;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["editableInPropertyPage"])("Use Manhattan Distance", _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_5__["PropertyTypeForEdition"].Boolean, "PROPERTIES", { "notifiers": { "update": false } })
], WorleyNoise3DBlock.prototype, "manhattanDistance", void 0);
return WorleyNoise3DBlock;
}(_nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlock"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].RegisteredTypes["BABYLON.WorleyNoise3DBlock"] = WorleyNoise3DBlock;
/***/ }),
/***/ "./Materials/Node/Enums/index.ts":
/*!***************************************!*\
!*** ./Materials/Node/Enums/index.ts ***!
\***************************************/
/*! exports provided: NodeMaterialBlockTargets, NodeMaterialBlockConnectionPointTypes, NodeMaterialBlockConnectionPointMode, NodeMaterialSystemValues, NodeMaterialModes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return _nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockTargets"]; });
/* harmony import */ var _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return _nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockConnectionPointTypes"]; });
/* harmony import */ var _nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPointMode */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointMode", function() { return _nodeMaterialBlockConnectionPointMode__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockConnectionPointMode"]; });
/* harmony import */ var _nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./nodeMaterialSystemValues */ "./Materials/Node/Enums/nodeMaterialSystemValues.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialSystemValues", function() { return _nodeMaterialSystemValues__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialSystemValues"]; });
/* harmony import */ var _nodeMaterialModes__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./nodeMaterialModes */ "./Materials/Node/Enums/nodeMaterialModes.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialModes", function() { return _nodeMaterialModes__WEBPACK_IMPORTED_MODULE_4__["NodeMaterialModes"]; });
/***/ }),
/***/ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.ts":
/*!**********************************************************************!*\
!*** ./Materials/Node/Enums/nodeMaterialBlockConnectionPointMode.ts ***!
\**********************************************************************/
/*! exports provided: NodeMaterialBlockConnectionPointMode */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointMode", function() { return NodeMaterialBlockConnectionPointMode; });
/**
* Enum defining the mode of a NodeMaterialBlockConnectionPoint
*/
var NodeMaterialBlockConnectionPointMode;
(function (NodeMaterialBlockConnectionPointMode) {
/** Value is an uniform */
NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Uniform"] = 0] = "Uniform";
/** Value is a mesh attribute */
NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Attribute"] = 1] = "Attribute";
/** Value is a varying between vertex and fragment shaders */
NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Varying"] = 2] = "Varying";
/** Mode is undefined */
NodeMaterialBlockConnectionPointMode[NodeMaterialBlockConnectionPointMode["Undefined"] = 3] = "Undefined";
})(NodeMaterialBlockConnectionPointMode || (NodeMaterialBlockConnectionPointMode = {}));
/***/ }),
/***/ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts":
/*!***********************************************************************!*\
!*** ./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts ***!
\***********************************************************************/
/*! exports provided: NodeMaterialBlockConnectionPointTypes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return NodeMaterialBlockConnectionPointTypes; });
/**
* Defines the kind of connection point for node based material
*/
var NodeMaterialBlockConnectionPointTypes;
(function (NodeMaterialBlockConnectionPointTypes) {
/** Float */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Float"] = 1] = "Float";
/** Int */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Int"] = 2] = "Int";
/** Vector2 */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector2"] = 4] = "Vector2";
/** Vector3 */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector3"] = 8] = "Vector3";
/** Vector4 */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Vector4"] = 16] = "Vector4";
/** Color3 */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color3"] = 32] = "Color3";
/** Color4 */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Color4"] = 64] = "Color4";
/** Matrix */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Matrix"] = 128] = "Matrix";
/** Custom object */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["Object"] = 256] = "Object";
/** Detect type based on connection */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["AutoDetect"] = 1024] = "AutoDetect";
/** Output type that will be defined by input type */
NodeMaterialBlockConnectionPointTypes[NodeMaterialBlockConnectionPointTypes["BasedOnInput"] = 2048] = "BasedOnInput";
})(NodeMaterialBlockConnectionPointTypes || (NodeMaterialBlockConnectionPointTypes = {}));
/***/ }),
/***/ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts":
/*!**********************************************************!*\
!*** ./Materials/Node/Enums/nodeMaterialBlockTargets.ts ***!
\**********************************************************/
/*! exports provided: NodeMaterialBlockTargets */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return NodeMaterialBlockTargets; });
/**
* Enum used to define the target of a block
*/
var NodeMaterialBlockTargets;
(function (NodeMaterialBlockTargets) {
/** Vertex shader */
NodeMaterialBlockTargets[NodeMaterialBlockTargets["Vertex"] = 1] = "Vertex";
/** Fragment shader */
NodeMaterialBlockTargets[NodeMaterialBlockTargets["Fragment"] = 2] = "Fragment";
/** Neutral */
NodeMaterialBlockTargets[NodeMaterialBlockTargets["Neutral"] = 4] = "Neutral";
/** Vertex and Fragment */
NodeMaterialBlockTargets[NodeMaterialBlockTargets["VertexAndFragment"] = 3] = "VertexAndFragment";
})(NodeMaterialBlockTargets || (NodeMaterialBlockTargets = {}));
/***/ }),
/***/ "./Materials/Node/Enums/nodeMaterialModes.ts":
/*!***************************************************!*\
!*** ./Materials/Node/Enums/nodeMaterialModes.ts ***!
\***************************************************/
/*! exports provided: NodeMaterialModes */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialModes", function() { return NodeMaterialModes; });
/**
* Enum used to define the material modes
*/
var NodeMaterialModes;
(function (NodeMaterialModes) {
/** Regular material */
NodeMaterialModes[NodeMaterialModes["Material"] = 0] = "Material";
/** For post process */
NodeMaterialModes[NodeMaterialModes["PostProcess"] = 1] = "PostProcess";
/** For particle system */
NodeMaterialModes[NodeMaterialModes["Particle"] = 2] = "Particle";
})(NodeMaterialModes || (NodeMaterialModes = {}));
/***/ }),
/***/ "./Materials/Node/Enums/nodeMaterialSystemValues.ts":
/*!**********************************************************!*\
!*** ./Materials/Node/Enums/nodeMaterialSystemValues.ts ***!
\**********************************************************/
/*! exports provided: NodeMaterialSystemValues */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialSystemValues", function() { return NodeMaterialSystemValues; });
/**
* Enum used to define system values e.g. values automatically provided by the system
*/
var NodeMaterialSystemValues;
(function (NodeMaterialSystemValues) {
/** World */
NodeMaterialSystemValues[NodeMaterialSystemValues["World"] = 1] = "World";
/** View */
NodeMaterialSystemValues[NodeMaterialSystemValues["View"] = 2] = "View";
/** Projection */
NodeMaterialSystemValues[NodeMaterialSystemValues["Projection"] = 3] = "Projection";
/** ViewProjection */
NodeMaterialSystemValues[NodeMaterialSystemValues["ViewProjection"] = 4] = "ViewProjection";
/** WorldView */
NodeMaterialSystemValues[NodeMaterialSystemValues["WorldView"] = 5] = "WorldView";
/** WorldViewProjection */
NodeMaterialSystemValues[NodeMaterialSystemValues["WorldViewProjection"] = 6] = "WorldViewProjection";
/** CameraPosition */
NodeMaterialSystemValues[NodeMaterialSystemValues["CameraPosition"] = 7] = "CameraPosition";
/** Fog Color */
NodeMaterialSystemValues[NodeMaterialSystemValues["FogColor"] = 8] = "FogColor";
/** Delta time */
NodeMaterialSystemValues[NodeMaterialSystemValues["DeltaTime"] = 9] = "DeltaTime";
})(NodeMaterialSystemValues || (NodeMaterialSystemValues = {}));
/***/ }),
/***/ "./Materials/Node/Optimizers/index.ts":
/*!********************************************!*\
!*** ./Materials/Node/Optimizers/index.ts ***!
\********************************************/
/*! exports provided: NodeMaterialOptimizer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _nodeMaterialOptimizer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./nodeMaterialOptimizer */ "./Materials/Node/Optimizers/nodeMaterialOptimizer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _nodeMaterialOptimizer__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialOptimizer"]; });
/***/ }),
/***/ "./Materials/Node/Optimizers/nodeMaterialOptimizer.ts":
/*!************************************************************!*\
!*** ./Materials/Node/Optimizers/nodeMaterialOptimizer.ts ***!
\************************************************************/
/*! exports provided: NodeMaterialOptimizer */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return NodeMaterialOptimizer; });
/**
* Root class for all node material optimizers
*/
var NodeMaterialOptimizer = /** @class */ (function () {
function NodeMaterialOptimizer() {
}
/**
* Function used to optimize a NodeMaterial graph
* @param vertexOutputNodes defines the list of output nodes for the vertex shader
* @param fragmentOutputNodes defines the list of output nodes for the fragment shader
*/
NodeMaterialOptimizer.prototype.optimize = function (vertexOutputNodes, fragmentOutputNodes) {
// Do nothing by default
};
return NodeMaterialOptimizer;
}());
/***/ }),
/***/ "./Materials/Node/index.ts":
/*!*********************************!*\
!*** ./Materials/Node/index.ts ***!
\*********************************/
/*! exports provided: NodeMaterialBlockTargets, NodeMaterialBlockConnectionPointTypes, NodeMaterialBlockConnectionPointMode, NodeMaterialSystemValues, NodeMaterialModes, NodeMaterialConnectionPointCompatibilityStates, NodeMaterialConnectionPointDirection, NodeMaterialConnectionPoint, NodeMaterialBlock, NodeMaterialDefines, NodeMaterial, VertexOutputBlock, BonesBlock, InstancesBlock, MorphTargetsBlock, LightInformationBlock, FragmentOutputBlock, ImageProcessingBlock, PerturbNormalBlock, DiscardBlock, FrontFacingBlock, DerivativeBlock, FragCoordBlock, ScreenSizeBlock, FogBlock, LightBlock, TextureBlock, ReflectionTextureBlock, CurrentScreenBlock, InputBlock, AnimatedInputBlockTypes, MultiplyBlock, AddBlock, ScaleBlock, ClampBlock, CrossBlock, DotBlock, TransformBlock, RemapBlock, NormalizeBlock, TrigonometryBlockOperations, TrigonometryBlock, ColorMergerBlock, VectorMergerBlock, ColorSplitterBlock, VectorSplitterBlock, LerpBlock, DivideBlock, SubtractBlock, StepBlock, OneMinusBlock, ViewDirectionBlock, FresnelBlock, MaxBlock, MinBlock, DistanceBlock, LengthBlock, NegateBlock, PowBlock, RandomNumberBlock, ArcTan2Block, SmoothStepBlock, ReciprocalBlock, ReplaceColorBlock, PosterizeBlock, WaveBlockKind, WaveBlock, GradientBlockColorStep, GradientBlock, NLerpBlock, WorleyNoise3DBlock, SimplexPerlin3DBlock, NormalBlendBlock, Rotate2dBlock, ReflectBlock, RefractBlock, DesaturateBlock, PBRMetallicRoughnessBlock, SheenBlock, AmbientOcclusionBlock, ReflectivityBlock, AnisotropyBlock, ReflectionBlock, ClearCoatBlock, RefractionBlock, SubSurfaceBlock, ParticleTextureBlock, ParticleRampGradientBlock, ParticleBlendMultiplyBlock, ModBlock, NodeMaterialOptimizer, PropertyTypeForEdition, editableInPropertyPage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _Enums_index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Enums/index */ "./Materials/Node/Enums/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockTargets", function() { return _Enums_index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockTargets"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointTypes", function() { return _Enums_index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlockConnectionPointMode", function() { return _Enums_index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointMode"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialSystemValues", function() { return _Enums_index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialSystemValues"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialModes", function() { return _Enums_index__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialModes"]; });
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointCompatibilityStates", function() { return _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPointCompatibilityStates"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointDirection", function() { return _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPointDirection"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPoint"]; });
/* harmony import */ var _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./nodeMaterialBlock */ "./Materials/Node/nodeMaterialBlock.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return _nodeMaterialBlock__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlock"]; });
/* harmony import */ var _nodeMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./nodeMaterial */ "./Materials/Node/nodeMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return _nodeMaterial__WEBPACK_IMPORTED_MODULE_3__["NodeMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return _nodeMaterial__WEBPACK_IMPORTED_MODULE_3__["NodeMaterial"]; });
/* harmony import */ var _Blocks_index__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./Blocks/index */ "./Materials/Node/Blocks/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VertexOutputBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["VertexOutputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "BonesBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["BonesBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InstancesBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["InstancesBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MorphTargetsBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["MorphTargetsBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightInformationBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["LightInformationBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragmentOutputBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["FragmentOutputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ImageProcessingBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ImageProcessingBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PerturbNormalBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["PerturbNormalBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DiscardBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["DiscardBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FrontFacingBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["FrontFacingBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DerivativeBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["DerivativeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FragCoordBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["FragCoordBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScreenSizeBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ScreenSizeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FogBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["FogBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LightBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["LightBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TextureBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["TextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionTextureBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ReflectionTextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CurrentScreenBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["CurrentScreenBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "InputBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["InputBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnimatedInputBlockTypes", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["AnimatedInputBlockTypes"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MultiplyBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["MultiplyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AddBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["AddBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ScaleBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ScaleBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClampBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ClampBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CrossBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["CrossBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DotBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["DotBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TransformBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["TransformBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RemapBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["RemapBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NormalizeBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["NormalizeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlockOperations", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["TrigonometryBlockOperations"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TrigonometryBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["TrigonometryBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorMergerBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ColorMergerBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VectorMergerBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["VectorMergerBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorSplitterBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ColorSplitterBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VectorSplitterBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["VectorSplitterBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LerpBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["LerpBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DivideBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["DivideBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubtractBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["SubtractBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StepBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["StepBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OneMinusBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["OneMinusBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ViewDirectionBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ViewDirectionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "FresnelBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["FresnelBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MaxBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["MaxBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MinBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["MinBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DistanceBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["DistanceBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "LengthBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["LengthBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NegateBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["NegateBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PowBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["PowBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RandomNumberBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["RandomNumberBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ArcTan2Block", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ArcTan2Block"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SmoothStepBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["SmoothStepBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReciprocalBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ReciprocalBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReplaceColorBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ReplaceColorBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PosterizeBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["PosterizeBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WaveBlockKind", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["WaveBlockKind"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WaveBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["WaveBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientBlockColorStep", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["GradientBlockColorStep"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GradientBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["GradientBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NLerpBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["NLerpBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "WorleyNoise3DBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["WorleyNoise3DBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SimplexPerlin3DBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["SimplexPerlin3DBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NormalBlendBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["NormalBlendBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Rotate2dBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["Rotate2dBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ReflectBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["RefractBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "DesaturateBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["DesaturateBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["PBRMetallicRoughnessBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SheenBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["SheenBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AmbientOcclusionBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["AmbientOcclusionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectivityBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ReflectivityBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AnisotropyBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["AnisotropyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ReflectionBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ReflectionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ClearCoatBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ClearCoatBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "RefractionBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["RefractionBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "SubSurfaceBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["SubSurfaceBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleTextureBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ParticleTextureBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleRampGradientBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ParticleRampGradientBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ParticleBlendMultiplyBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ParticleBlendMultiplyBlock"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ModBlock", function() { return _Blocks_index__WEBPACK_IMPORTED_MODULE_4__["ModBlock"]; });
/* harmony import */ var _Optimizers_index__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./Optimizers/index */ "./Materials/Node/Optimizers/index.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialOptimizer", function() { return _Optimizers_index__WEBPACK_IMPORTED_MODULE_5__["NodeMaterialOptimizer"]; });
/* harmony import */ var _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./nodeMaterialDecorator */ "./Materials/Node/nodeMaterialDecorator.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PropertyTypeForEdition", function() { return _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["PropertyTypeForEdition"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "editableInPropertyPage", function() { return _nodeMaterialDecorator__WEBPACK_IMPORTED_MODULE_6__["editableInPropertyPage"]; });
/***/ }),
/***/ "./Materials/Node/nodeMaterial.ts":
/*!****************************************!*\
!*** ./Materials/Node/nodeMaterial.ts ***!
\****************************************/
/*! exports provided: NodeMaterialDefines, NodeMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialDefines", function() { return NodeMaterialDefines; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterial", function() { return NodeMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _pushMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../pushMaterial */ "./Materials/pushMaterial.ts");
/* harmony import */ var _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/abstractMesh */ "./Meshes/abstractMesh.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _nodeMaterialBuildState__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./nodeMaterialBuildState */ "./Materials/Node/nodeMaterialBuildState.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _nodeMaterialBuildStateSharedData__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./nodeMaterialBuildStateSharedData */ "./Materials/Node/nodeMaterialBuildStateSharedData.ts");
/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ../../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Blocks_transformBlock__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ./Blocks/transformBlock */ "./Materials/Node/Blocks/transformBlock.ts");
/* harmony import */ var _Blocks_Vertex_vertexOutputBlock__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ./Blocks/Vertex/vertexOutputBlock */ "./Materials/Node/Blocks/Vertex/vertexOutputBlock.ts");
/* harmony import */ var _Blocks_Fragment_fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ./Blocks/Fragment/fragmentOutputBlock */ "./Materials/Node/Blocks/Fragment/fragmentOutputBlock.ts");
/* harmony import */ var _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ./Blocks/Input/inputBlock */ "./Materials/Node/Blocks/Input/inputBlock.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Blocks_Dual_currentScreenBlock__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./Blocks/Dual/currentScreenBlock */ "./Materials/Node/Blocks/Dual/currentScreenBlock.ts");
/* harmony import */ var _Blocks_Particle_particleTextureBlock__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ./Blocks/Particle/particleTextureBlock */ "./Materials/Node/Blocks/Particle/particleTextureBlock.ts");
/* harmony import */ var _Blocks_Particle_particleRampGradientBlock__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ./Blocks/Particle/particleRampGradientBlock */ "./Materials/Node/Blocks/Particle/particleRampGradientBlock.ts");
/* harmony import */ var _Blocks_Particle_particleBlendMultiplyBlock__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ./Blocks/Particle/particleBlendMultiplyBlock */ "./Materials/Node/Blocks/Particle/particleBlendMultiplyBlock.ts");
/* harmony import */ var _effectFallbacks__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../effectFallbacks */ "./Materials/effectFallbacks.ts");
/* harmony import */ var _Misc_webRequest__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Misc/webRequest */ "./Misc/webRequest.ts");
/* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../effect */ "./Materials/effect.ts");
/* harmony import */ var _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../../PostProcesses/postProcess */ "./PostProcesses/postProcess.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Blocks_vectorMergerBlock__WEBPACK_IMPORTED_MODULE_28__ = __webpack_require__(/*! ./Blocks/vectorMergerBlock */ "./Materials/Node/Blocks/vectorMergerBlock.ts");
/* harmony import */ var _Blocks_remapBlock__WEBPACK_IMPORTED_MODULE_29__ = __webpack_require__(/*! ./Blocks/remapBlock */ "./Materials/Node/Blocks/remapBlock.ts");
/* harmony import */ var _Blocks_multiplyBlock__WEBPACK_IMPORTED_MODULE_30__ = __webpack_require__(/*! ./Blocks/multiplyBlock */ "./Materials/Node/Blocks/multiplyBlock.ts");
/* harmony import */ var _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__ = __webpack_require__(/*! ./Enums/nodeMaterialModes */ "./Materials/Node/Enums/nodeMaterialModes.ts");
/* harmony import */ var _Textures_texture__WEBPACK_IMPORTED_MODULE_32__ = __webpack_require__(/*! ../Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _Particles_baseParticleSystem__WEBPACK_IMPORTED_MODULE_33__ = __webpack_require__(/*! ../../Particles/baseParticleSystem */ "./Particles/baseParticleSystem.ts");
/* harmony import */ var _Blocks_colorSplitterBlock__WEBPACK_IMPORTED_MODULE_34__ = __webpack_require__(/*! ./Blocks/colorSplitterBlock */ "./Materials/Node/Blocks/colorSplitterBlock.ts");
/* harmony import */ var _Misc_timingTools__WEBPACK_IMPORTED_MODULE_35__ = __webpack_require__(/*! ../../Misc/timingTools */ "./Misc/timingTools.ts");
var onCreatedEffectParameters = { effect: null, subMesh: null };
/** @hidden */
var NodeMaterialDefines = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NodeMaterialDefines, _super);
function NodeMaterialDefines() {
var _this = _super.call(this) || this;
_this.NORMAL = false;
_this.TANGENT = false;
_this.UV1 = false;
/** BONES */
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.BONETEXTURE = false;
/** MORPH TARGETS */
_this.MORPHTARGETS = false;
_this.MORPHTARGETS_NORMAL = false;
_this.MORPHTARGETS_TANGENT = false;
_this.MORPHTARGETS_UV = false;
_this.NUM_MORPH_INFLUENCERS = 0;
/** IMAGE PROCESSING */
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.EXPOSURE = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
/** MISC. */
_this.BUMPDIRECTUV = 0;
_this.rebuild();
return _this;
}
NodeMaterialDefines.prototype.setValue = function (name, value, markAsUnprocessedIfDirty) {
if (markAsUnprocessedIfDirty === void 0) { markAsUnprocessedIfDirty = false; }
if (this[name] === undefined) {
this._keys.push(name);
}
if (markAsUnprocessedIfDirty && this[name] !== value) {
this.markAsUnprocessed();
}
this[name] = value;
};
return NodeMaterialDefines;
}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_10__["MaterialDefines"]));
/**
* Class used to create a node based material built by assembling shader blocks
*/
var NodeMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NodeMaterial, _super);
/**
* Create a new node based material
* @param name defines the material name
* @param scene defines the hosting scene
* @param options defines creation option
*/
function NodeMaterial(name, scene, options) {
if (options === void 0) { options = {}; }
var _this = _super.call(this, name, scene || _Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].LastCreatedScene) || this;
_this._buildId = NodeMaterial._BuildIdGenerator++;
_this._buildWasSuccessful = false;
_this._cachedWorldViewMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
_this._cachedWorldViewProjectionMatrix = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Matrix"]();
_this._optimizers = new Array();
_this._animationFrame = -1;
_this.BJSNODEMATERIALEDITOR = _this._getGlobalNodeMaterialEditor();
/**
* Gets or sets data used by visual editor
* @see https://nme.babylonjs.com
*/
_this.editorData = null;
/**
* Gets or sets a boolean indicating that alpha value must be ignored (This will turn alpha blending off even if an alpha value is produced by the material)
*/
_this.ignoreAlpha = false;
/**
* Defines the maximum number of lights that can be used in the material
*/
_this.maxSimultaneousLights = 4;
/**
* Observable raised when the material is built
*/
_this.onBuildObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_7__["Observable"]();
/**
* Gets or sets the root nodes of the material vertex shader
*/
_this._vertexOutputNodes = new Array();
/**
* Gets or sets the root nodes of the material fragment (pixel) shader
*/
_this._fragmentOutputNodes = new Array();
/**
* Gets an array of blocks that needs to be serialized even if they are not yet connected
*/
_this.attachedBlocks = new Array();
/**
* Specifies the mode of the node material
* @hidden
*/
_this._mode = _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__["NodeMaterialModes"].Material;
_this._options = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ emitComments: false }, options);
// Setup the default processing configuration to the scene.
_this._attachImageProcessingConfiguration(null);
return _this;
}
/** Get the inspector from bundle or global */
NodeMaterial.prototype._getGlobalNodeMaterialEditor = function () {
// UMD Global name detection from Webpack Bundle UMD Name.
if (typeof NODEEDITOR !== 'undefined') {
return NODEEDITOR;
}
// In case of module let's check the global emitted from the editor entry point.
if (typeof BABYLON !== 'undefined' && typeof BABYLON.NodeEditor !== 'undefined') {
return BABYLON;
}
return undefined;
};
Object.defineProperty(NodeMaterial.prototype, "options", {
/** Gets or sets options to control the node material overall behavior */
get: function () {
return this._options;
},
set: function (options) {
this._options = options;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterial.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function () {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function (value) {
this._attachImageProcessingConfiguration(value);
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterial.prototype, "mode", {
/**
* Gets the mode property
*/
get: function () {
return this._mode;
},
enumerable: false,
configurable: true
});
/**
* Gets the current class name of the material e.g. "NodeMaterial"
* @returns the class name
*/
NodeMaterial.prototype.getClassName = function () {
return "NodeMaterial";
};
/**
* Attaches a new image processing configuration to the Standard Material.
* @param configuration
*/
NodeMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
// Detaches observer.
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
// Pick the scene configuration if needed.
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
}
else {
this._imageProcessingConfiguration = configuration;
}
// Attaches observer.
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () {
_this._markAllSubMeshesAsImageProcessingDirty();
});
}
};
/**
* Get a block by its name
* @param name defines the name of the block to retrieve
* @returns the required block or null if not found
*/
NodeMaterial.prototype.getBlockByName = function (name) {
var result = null;
for (var _i = 0, _a = this.attachedBlocks; _i < _a.length; _i++) {
var block = _a[_i];
if (block.name === name) {
if (!result) {
result = block;
}
else {
_Misc_tools__WEBPACK_IMPORTED_MODULE_12__["Tools"].Warn("More than one block was found with the name `" + name + "`");
return result;
}
}
}
return result;
};
/**
* Get a block by its name
* @param predicate defines the predicate used to find the good candidate
* @returns the required block or null if not found
*/
NodeMaterial.prototype.getBlockByPredicate = function (predicate) {
for (var _i = 0, _a = this.attachedBlocks; _i < _a.length; _i++) {
var block = _a[_i];
if (predicate(block)) {
return block;
}
}
return null;
};
/**
* Get an input block by its name
* @param predicate defines the predicate used to find the good candidate
* @returns the required input block or null if not found
*/
NodeMaterial.prototype.getInputBlockByPredicate = function (predicate) {
for (var _i = 0, _a = this.attachedBlocks; _i < _a.length; _i++) {
var block = _a[_i];
if (block.isInput && predicate(block)) {
return block;
}
}
return null;
};
/**
* Gets the list of input blocks attached to this material
* @returns an array of InputBlocks
*/
NodeMaterial.prototype.getInputBlocks = function () {
var blocks = [];
for (var _i = 0, _a = this.attachedBlocks; _i < _a.length; _i++) {
var block = _a[_i];
if (block.isInput) {
blocks.push(block);
}
}
return blocks;
};
/**
* Adds a new optimizer to the list of optimizers
* @param optimizer defines the optimizers to add
* @returns the current material
*/
NodeMaterial.prototype.registerOptimizer = function (optimizer) {
var index = this._optimizers.indexOf(optimizer);
if (index > -1) {
return;
}
this._optimizers.push(optimizer);
return this;
};
/**
* Remove an optimizer from the list of optimizers
* @param optimizer defines the optimizers to remove
* @returns the current material
*/
NodeMaterial.prototype.unregisterOptimizer = function (optimizer) {
var index = this._optimizers.indexOf(optimizer);
if (index === -1) {
return;
}
this._optimizers.splice(index, 1);
return this;
};
/**
* Add a new block to the list of output nodes
* @param node defines the node to add
* @returns the current material
*/
NodeMaterial.prototype.addOutputNode = function (node) {
if (node.target === null) {
throw "This node is not meant to be an output node. You may want to explicitly set its target value.";
}
if ((node.target & _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex) !== 0) {
this._addVertexOutputNode(node);
}
if ((node.target & _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment) !== 0) {
this._addFragmentOutputNode(node);
}
return this;
};
/**
* Remove a block from the list of root nodes
* @param node defines the node to remove
* @returns the current material
*/
NodeMaterial.prototype.removeOutputNode = function (node) {
if (node.target === null) {
return this;
}
if ((node.target & _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex) !== 0) {
this._removeVertexOutputNode(node);
}
if ((node.target & _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment) !== 0) {
this._removeFragmentOutputNode(node);
}
return this;
};
NodeMaterial.prototype._addVertexOutputNode = function (node) {
if (this._vertexOutputNodes.indexOf(node) !== -1) {
return;
}
node.target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex;
this._vertexOutputNodes.push(node);
return this;
};
NodeMaterial.prototype._removeVertexOutputNode = function (node) {
var index = this._vertexOutputNodes.indexOf(node);
if (index === -1) {
return;
}
this._vertexOutputNodes.splice(index, 1);
return this;
};
NodeMaterial.prototype._addFragmentOutputNode = function (node) {
if (this._fragmentOutputNodes.indexOf(node) !== -1) {
return;
}
node.target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment;
this._fragmentOutputNodes.push(node);
return this;
};
NodeMaterial.prototype._removeFragmentOutputNode = function (node) {
var index = this._fragmentOutputNodes.indexOf(node);
if (index === -1) {
return;
}
this._fragmentOutputNodes.splice(index, 1);
return this;
};
/**
* Specifies if the material will require alpha blending
* @returns a boolean specifying if alpha blending is needed
*/
NodeMaterial.prototype.needAlphaBlending = function () {
if (this.ignoreAlpha) {
return false;
}
return (this.alpha < 1.0) || (this._sharedData && this._sharedData.hints.needAlphaBlending);
};
/**
* Specifies if this material should be rendered in alpha test mode
* @returns a boolean specifying if an alpha test is needed.
*/
NodeMaterial.prototype.needAlphaTesting = function () {
return this._sharedData && this._sharedData.hints.needAlphaTesting;
};
NodeMaterial.prototype._initializeBlock = function (node, state, nodesToProcessForOtherBuildState) {
node.initialize(state);
node.autoConfigure(this);
node._preparationId = this._buildId;
if (this.attachedBlocks.indexOf(node) === -1) {
if (node.isUnique) {
var className = node.getClassName();
for (var _i = 0, _a = this.attachedBlocks; _i < _a.length; _i++) {
var other = _a[_i];
if (other.getClassName() === className) {
throw "Cannot have multiple blocks of type " + className + " in the same NodeMaterial";
}
}
}
this.attachedBlocks.push(node);
}
for (var _b = 0, _c = node.inputs; _b < _c.length; _b++) {
var input = _c[_b];
input.associatedVariableName = "";
var connectedPoint = input.connectedPoint;
if (connectedPoint) {
var block = connectedPoint.ownerBlock;
if (block !== node) {
if (block.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].VertexAndFragment) {
nodesToProcessForOtherBuildState.push(block);
}
else if (state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment
&& block.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex
&& block._preparationId !== this._buildId) {
nodesToProcessForOtherBuildState.push(block);
}
this._initializeBlock(block, state, nodesToProcessForOtherBuildState);
}
}
}
for (var _d = 0, _e = node.outputs; _d < _e.length; _d++) {
var output = _e[_d];
output.associatedVariableName = "";
}
};
NodeMaterial.prototype._resetDualBlocks = function (node, id) {
if (node.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].VertexAndFragment) {
node.buildId = id;
}
for (var _i = 0, _a = node.inputs; _i < _a.length; _i++) {
var inputs = _a[_i];
var connectedPoint = inputs.connectedPoint;
if (connectedPoint) {
var block = connectedPoint.ownerBlock;
if (block !== node) {
this._resetDualBlocks(block, id);
}
}
}
};
/**
* Remove a block from the current node material
* @param block defines the block to remove
*/
NodeMaterial.prototype.removeBlock = function (block) {
var attachedBlockIndex = this.attachedBlocks.indexOf(block);
if (attachedBlockIndex > -1) {
this.attachedBlocks.splice(attachedBlockIndex, 1);
}
if (block.isFinalMerger) {
this.removeOutputNode(block);
}
};
/**
* Build the material and generates the inner effect
* @param verbose defines if the build should log activity
*/
NodeMaterial.prototype.build = function (verbose) {
if (verbose === void 0) { verbose = false; }
this._buildWasSuccessful = false;
var engine = this.getScene().getEngine();
var allowEmptyVertexProgram = this._mode === _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__["NodeMaterialModes"].Particle;
if (this._vertexOutputNodes.length === 0 && !allowEmptyVertexProgram) {
throw "You must define at least one vertexOutputNode";
}
if (this._fragmentOutputNodes.length === 0) {
throw "You must define at least one fragmentOutputNode";
}
// Compilation state
this._vertexCompilationState = new _nodeMaterialBuildState__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialBuildState"]();
this._vertexCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
this._vertexCompilationState.target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Vertex;
this._fragmentCompilationState = new _nodeMaterialBuildState__WEBPACK_IMPORTED_MODULE_6__["NodeMaterialBuildState"]();
this._fragmentCompilationState.supportUniformBuffers = engine.supportsUniformBuffers;
this._fragmentCompilationState.target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_8__["NodeMaterialBlockTargets"].Fragment;
// Shared data
this._sharedData = new _nodeMaterialBuildStateSharedData__WEBPACK_IMPORTED_MODULE_9__["NodeMaterialBuildStateSharedData"]();
this._vertexCompilationState.sharedData = this._sharedData;
this._fragmentCompilationState.sharedData = this._sharedData;
this._sharedData.buildId = this._buildId;
this._sharedData.emitComments = this._options.emitComments;
this._sharedData.verbose = verbose;
this._sharedData.scene = this.getScene();
this._sharedData.allowEmptyVertexProgram = allowEmptyVertexProgram;
// Initialize blocks
var vertexNodes = [];
var fragmentNodes = [];
for (var _i = 0, _a = this._vertexOutputNodes; _i < _a.length; _i++) {
var vertexOutputNode = _a[_i];
vertexNodes.push(vertexOutputNode);
this._initializeBlock(vertexOutputNode, this._vertexCompilationState, fragmentNodes);
}
for (var _b = 0, _c = this._fragmentOutputNodes; _b < _c.length; _b++) {
var fragmentOutputNode = _c[_b];
fragmentNodes.push(fragmentOutputNode);
this._initializeBlock(fragmentOutputNode, this._fragmentCompilationState, vertexNodes);
}
// Optimize
this.optimize();
// Vertex
for (var _d = 0, vertexNodes_1 = vertexNodes; _d < vertexNodes_1.length; _d++) {
var vertexOutputNode = vertexNodes_1[_d];
vertexOutputNode.build(this._vertexCompilationState, vertexNodes);
}
// Fragment
this._fragmentCompilationState.uniforms = this._vertexCompilationState.uniforms.slice(0);
this._fragmentCompilationState._uniformDeclaration = this._vertexCompilationState._uniformDeclaration;
this._fragmentCompilationState._constantDeclaration = this._vertexCompilationState._constantDeclaration;
this._fragmentCompilationState._vertexState = this._vertexCompilationState;
for (var _e = 0, fragmentNodes_1 = fragmentNodes; _e < fragmentNodes_1.length; _e++) {
var fragmentOutputNode = fragmentNodes_1[_e];
this._resetDualBlocks(fragmentOutputNode, this._buildId - 1);
}
for (var _f = 0, fragmentNodes_2 = fragmentNodes; _f < fragmentNodes_2.length; _f++) {
var fragmentOutputNode = fragmentNodes_2[_f];
fragmentOutputNode.build(this._fragmentCompilationState, fragmentNodes);
}
// Finalize
this._vertexCompilationState.finalize(this._vertexCompilationState);
this._fragmentCompilationState.finalize(this._fragmentCompilationState);
this._buildId = NodeMaterial._BuildIdGenerator++;
// Errors
this._sharedData.emitErrors();
if (verbose) {
console.log("Vertex shader:");
console.log(this._vertexCompilationState.compilationString);
console.log("Fragment shader:");
console.log(this._fragmentCompilationState.compilationString);
}
this._buildWasSuccessful = true;
this.onBuildObservable.notifyObservers(this);
// Wipe defines
var meshes = this.getScene().meshes;
for (var _g = 0, meshes_1 = meshes; _g < meshes_1.length; _g++) {
var mesh = meshes_1[_g];
if (!mesh.subMeshes) {
continue;
}
for (var _h = 0, _j = mesh.subMeshes; _h < _j.length; _h++) {
var subMesh = _j[_h];
if (subMesh.getMaterial() !== this) {
continue;
}
if (!subMesh._materialDefines) {
continue;
}
var defines = subMesh._materialDefines;
defines.markAllAsDirty();
defines.reset();
}
}
};
/**
* Runs an otpimization phase to try to improve the shader code
*/
NodeMaterial.prototype.optimize = function () {
for (var _i = 0, _a = this._optimizers; _i < _a.length; _i++) {
var optimizer = _a[_i];
optimizer.optimize(this._vertexOutputNodes, this._fragmentOutputNodes);
}
};
NodeMaterial.prototype._prepareDefinesForAttributes = function (mesh, defines) {
var oldNormal = defines["NORMAL"];
var oldTangent = defines["TANGENT"];
var oldUV1 = defines["UV1"];
defines["NORMAL"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__["VertexBuffer"].NormalKind);
defines["TANGENT"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__["VertexBuffer"].TangentKind);
defines["UV1"] = mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_11__["VertexBuffer"].UVKind);
if (oldNormal !== defines["NORMAL"] || oldTangent !== defines["TANGENT"] || oldUV1 !== defines["UV1"]) {
defines.markAsAttributesDirty();
}
};
/**
* Create a post process from the material
* @param camera The camera to apply the render pass to.
* @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
* @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
* @param engine The engine which the post process will be applied. (default: current engine)
* @param reusable If the post process can be reused on the same frame. (default: false)
* @param textureType Type of textures used when performing the post process. (default: 0)
* @param textureFormat Format of textures used when performing the post process. (default: TEXTUREFORMAT_RGBA)
* @returns the post process created
*/
NodeMaterial.prototype.createPostProcess = function (camera, options, samplingMode, engine, reusable, textureType, textureFormat) {
if (options === void 0) { options = 1; }
if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_27__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE; }
if (textureType === void 0) { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_27__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
if (textureFormat === void 0) { textureFormat = _Engines_constants__WEBPACK_IMPORTED_MODULE_27__["Constants"].TEXTUREFORMAT_RGBA; }
return this._createEffectOrPostProcess(null, camera, options, samplingMode, engine, reusable, textureType, textureFormat);
};
/**
* Create the post process effect from the material
* @param postProcess The post process to create the effect for
*/
NodeMaterial.prototype.createEffectForPostProcess = function (postProcess) {
this._createEffectOrPostProcess(postProcess);
};
NodeMaterial.prototype._createEffectOrPostProcess = function (postProcess, camera, options, samplingMode, engine, reusable, textureType, textureFormat) {
var _this = this;
if (options === void 0) { options = 1; }
if (samplingMode === void 0) { samplingMode = _Engines_constants__WEBPACK_IMPORTED_MODULE_27__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE; }
if (textureType === void 0) { textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_27__["Constants"].TEXTURETYPE_UNSIGNED_INT; }
if (textureFormat === void 0) { textureFormat = _Engines_constants__WEBPACK_IMPORTED_MODULE_27__["Constants"].TEXTUREFORMAT_RGBA; }
var tempName = this.name + this._buildId;
var defines = new NodeMaterialDefines();
var dummyMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"](tempName + "PostProcess", this.getScene());
var buildId = this._buildId;
this._processDefines(dummyMesh, defines);
_effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString, this._vertexCompilationState._builtCompilationString);
if (!postProcess) {
postProcess = new _PostProcesses_postProcess__WEBPACK_IMPORTED_MODULE_26__["PostProcess"](this.name + "PostProcess", tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, options, camera, samplingMode, engine, reusable, defines.toString(), textureType, tempName, { maxSimultaneousLights: this.maxSimultaneousLights }, false, textureFormat);
}
else {
postProcess.updateEffect(defines.toString(), this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, { maxSimultaneousLights: this.maxSimultaneousLights }, undefined, undefined, tempName, tempName);
}
postProcess.nodeMaterialSource = this;
postProcess.onApplyObservable.add(function (effect) {
if (buildId !== _this._buildId) {
delete _effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].ShadersStore[tempName + "VertexShader"];
delete _effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].ShadersStore[tempName + "PixelShader"];
tempName = _this.name + _this._buildId;
defines.markAsUnprocessed();
buildId = _this._buildId;
}
var result = _this._processDefines(dummyMesh, defines);
if (result) {
_effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].RegisterShader(tempName, _this._fragmentCompilationState._builtCompilationString, _this._vertexCompilationState._builtCompilationString);
_Misc_timingTools__WEBPACK_IMPORTED_MODULE_35__["TimingTools"].SetImmediate(function () {
return postProcess.updateEffect(defines.toString(), _this._fragmentCompilationState.uniforms, _this._fragmentCompilationState.samplers, { maxSimultaneousLights: _this.maxSimultaneousLights }, undefined, undefined, tempName, tempName);
});
}
// Animated blocks
if (_this._sharedData.animatedInputs) {
var scene = _this.getScene();
var frameId = scene.getFrameId();
if (_this._animationFrame !== frameId) {
for (var _i = 0, _a = _this._sharedData.animatedInputs; _i < _a.length; _i++) {
var input = _a[_i];
input.animate(scene);
}
_this._animationFrame = frameId;
}
}
// Bindable blocks
for (var _b = 0, _c = _this._sharedData.bindableBlocks; _b < _c.length; _b++) {
var block = _c[_b];
block.bind(effect, _this);
}
// Connection points
for (var _d = 0, _e = _this._sharedData.inputBlocks; _d < _e.length; _d++) {
var inputBlock = _e[_d];
inputBlock._transmit(effect, _this.getScene());
}
});
return postProcess;
};
NodeMaterial.prototype._createEffectForParticles = function (particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined_) {
var _this = this;
if (particleSystemDefinesJoined_ === void 0) { particleSystemDefinesJoined_ = ""; }
var tempName = this.name + this._buildId + "_" + blendMode;
if (!defines) {
defines = new NodeMaterialDefines();
}
if (!dummyMesh) {
dummyMesh = this.getScene().getMeshByName(this.name + "Particle");
if (!dummyMesh) {
dummyMesh = new _Meshes_abstractMesh__WEBPACK_IMPORTED_MODULE_2__["AbstractMesh"](this.name + "Particle", this.getScene());
}
}
var buildId = this._buildId;
var particleSystemDefines = [];
var particleSystemDefinesJoined = particleSystemDefinesJoined_;
if (!effect) {
var result = this._processDefines(dummyMesh, defines);
_effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].RegisterShader(tempName, this._fragmentCompilationState._builtCompilationString);
particleSystem.fillDefines(particleSystemDefines, blendMode);
particleSystemDefinesJoined = particleSystemDefines.join("\n");
effect = this.getScene().getEngine().createEffectForParticles(tempName, this._fragmentCompilationState.uniforms, this._fragmentCompilationState.samplers, defines.toString() + "\n" + particleSystemDefinesJoined, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem);
particleSystem.setCustomEffect(effect, blendMode);
}
effect.onBindObservable.add(function (effect) {
if (buildId !== _this._buildId) {
delete _effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].ShadersStore[tempName + "PixelShader"];
tempName = _this.name + _this._buildId + "_" + blendMode;
defines.markAsUnprocessed();
buildId = _this._buildId;
}
particleSystemDefines.length = 0;
particleSystem.fillDefines(particleSystemDefines, blendMode);
var particleSystemDefinesJoinedCurrent = particleSystemDefines.join("\n");
if (particleSystemDefinesJoinedCurrent !== particleSystemDefinesJoined) {
defines.markAsUnprocessed();
particleSystemDefinesJoined = particleSystemDefinesJoinedCurrent;
}
var result = _this._processDefines(dummyMesh, defines);
if (result) {
_effect__WEBPACK_IMPORTED_MODULE_25__["Effect"].RegisterShader(tempName, _this._fragmentCompilationState._builtCompilationString);
effect = _this.getScene().getEngine().createEffectForParticles(tempName, _this._fragmentCompilationState.uniforms, _this._fragmentCompilationState.samplers, defines.toString() + "\n" + particleSystemDefinesJoined, result === null || result === void 0 ? void 0 : result.fallbacks, onCompiled, onError, particleSystem);
particleSystem.setCustomEffect(effect, blendMode);
_this._createEffectForParticles(particleSystem, blendMode, onCompiled, onError, effect, defines, dummyMesh, particleSystemDefinesJoined); // add the effect.onBindObservable observer
return;
}
// Animated blocks
if (_this._sharedData.animatedInputs) {
var scene = _this.getScene();
var frameId = scene.getFrameId();
if (_this._animationFrame !== frameId) {
for (var _i = 0, _a = _this._sharedData.animatedInputs; _i < _a.length; _i++) {
var input = _a[_i];
input.animate(scene);
}
_this._animationFrame = frameId;
}
}
// Bindable blocks
for (var _b = 0, _c = _this._sharedData.bindableBlocks; _b < _c.length; _b++) {
var block = _c[_b];
block.bind(effect, _this);
}
// Connection points
for (var _d = 0, _e = _this._sharedData.inputBlocks; _d < _e.length; _d++) {
var inputBlock = _e[_d];
inputBlock._transmit(effect, _this.getScene());
}
});
};
/**
* Create the effect to be used as the custom effect for a particle system
* @param particleSystem Particle system to create the effect for
* @param onCompiled defines a function to call when the effect creation is successful
* @param onError defines a function to call when the effect creation has failed
*/
NodeMaterial.prototype.createEffectForParticles = function (particleSystem, onCompiled, onError) {
this._createEffectForParticles(particleSystem, _Particles_baseParticleSystem__WEBPACK_IMPORTED_MODULE_33__["BaseParticleSystem"].BLENDMODE_ONEONE, onCompiled, onError);
this._createEffectForParticles(particleSystem, _Particles_baseParticleSystem__WEBPACK_IMPORTED_MODULE_33__["BaseParticleSystem"].BLENDMODE_MULTIPLY, onCompiled, onError);
};
NodeMaterial.prototype._processDefines = function (mesh, defines, useInstances, subMesh) {
var _this = this;
if (useInstances === void 0) { useInstances = false; }
var result = null;
// Shared defines
this._sharedData.blocksWithDefines.forEach(function (b) {
b.initializeDefines(mesh, _this, defines, useInstances);
});
this._sharedData.blocksWithDefines.forEach(function (b) {
b.prepareDefines(mesh, _this, defines, useInstances, subMesh);
});
// Need to recompile?
if (defines.isDirty) {
var lightDisposed = defines._areLightsDisposed;
defines.markAsProcessed();
// Repeatable content generators
this._vertexCompilationState.compilationString = this._vertexCompilationState._builtCompilationString;
this._fragmentCompilationState.compilationString = this._fragmentCompilationState._builtCompilationString;
this._sharedData.repeatableContentBlocks.forEach(function (b) {
b.replaceRepeatableContent(_this._vertexCompilationState, _this._fragmentCompilationState, mesh, defines);
});
// Uniforms
var uniformBuffers_1 = [];
this._sharedData.dynamicUniformBlocks.forEach(function (b) {
b.updateUniformsAndSamples(_this._vertexCompilationState, _this, defines, uniformBuffers_1);
});
var mergedUniforms_1 = this._vertexCompilationState.uniforms;
this._fragmentCompilationState.uniforms.forEach(function (u) {
var index = mergedUniforms_1.indexOf(u);
if (index === -1) {
mergedUniforms_1.push(u);
}
});
// Samplers
var mergedSamplers_1 = this._vertexCompilationState.samplers;
this._fragmentCompilationState.samplers.forEach(function (s) {
var index = mergedSamplers_1.indexOf(s);
if (index === -1) {
mergedSamplers_1.push(s);
}
});
var fallbacks = new _effectFallbacks__WEBPACK_IMPORTED_MODULE_23__["EffectFallbacks"]();
this._sharedData.blocksWithFallbacks.forEach(function (b) {
b.provideFallbacks(mesh, fallbacks);
});
result = {
lightDisposed: lightDisposed,
uniformBuffers: uniformBuffers_1,
mergedUniforms: mergedUniforms_1,
mergedSamplers: mergedSamplers_1,
fallbacks: fallbacks,
};
}
return result;
};
/**
* Get if the submesh is ready to be used and all its information available.
* Child classes can use it to update shaders
* @param mesh defines the mesh to check
* @param subMesh defines which submesh to check
* @param useInstances specifies that instances should be used
* @returns a boolean indicating that the submesh is ready or not
*/
NodeMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
var _this = this;
if (useInstances === void 0) { useInstances = false; }
if (!this._buildWasSuccessful) {
return false;
}
var scene = this.getScene();
if (this._sharedData.animatedInputs) {
var frameId = scene.getFrameId();
if (this._animationFrame !== frameId) {
for (var _i = 0, _a = this._sharedData.animatedInputs; _i < _a.length; _i++) {
var input = _a[_i];
input.animate(scene);
}
this._animationFrame = frameId;
}
}
if (subMesh.effect && this.isFrozen) {
if (subMesh.effect._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new NodeMaterialDefines();
}
var defines = subMesh._materialDefines;
if (this._isReadyForSubMesh(subMesh)) {
return true;
}
var engine = scene.getEngine();
this._prepareDefinesForAttributes(mesh, defines);
// Check if blocks are ready
if (this._sharedData.blockingBlocks.some(function (b) { return !b.isReady(mesh, _this, defines, useInstances); })) {
return false;
}
var result = this._processDefines(mesh, defines, useInstances, subMesh);
if (result) {
var previousEffect = subMesh.effect;
// Compilation
var join = defines.toString();
var effect = engine.createEffect({
vertex: "nodeMaterial" + this._buildId,
fragment: "nodeMaterial" + this._buildId,
vertexSource: this._vertexCompilationState.compilationString,
fragmentSource: this._fragmentCompilationState.compilationString
}, {
attributes: this._vertexCompilationState.attributes,
uniformsNames: result.mergedUniforms,
uniformBuffersNames: result.uniformBuffers,
samplers: result.mergedSamplers,
defines: join,
fallbacks: result.fallbacks,
onCompiled: this.onCompiled,
onError: this.onError,
indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
}, engine);
if (effect) {
if (this._onEffectCreatedObservable) {
onCreatedEffectParameters.effect = effect;
onCreatedEffectParameters.subMesh = subMesh;
this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
}
// Use previous effect while new one is compiling
if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
effect = previousEffect;
defines.markAsUnprocessed();
if (result.lightDisposed) {
// re register in case it takes more than one frame.
defines._areLightsDisposed = true;
return false;
}
}
else {
scene.resetCachedMaterial();
subMesh.setEffect(effect, defines);
}
}
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
subMesh.effect._wasPreviouslyReady = true;
return true;
};
Object.defineProperty(NodeMaterial.prototype, "compiledShaders", {
/**
* Get a string representing the shaders built by the current node graph
*/
get: function () {
return "// Vertex shader\r\n" + this._vertexCompilationState.compilationString + "\r\n\r\n// Fragment shader\r\n" + this._fragmentCompilationState.compilationString;
},
enumerable: false,
configurable: true
});
/**
* Binds the world matrix to the material
* @param world defines the world transformation matrix
*/
NodeMaterial.prototype.bindOnlyWorldMatrix = function (world) {
var scene = this.getScene();
if (!this._activeEffect) {
return;
}
var hints = this._sharedData.hints;
if (hints.needWorldViewMatrix) {
world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
}
if (hints.needWorldViewProjectionMatrix) {
world.multiplyToRef(scene.getTransformMatrix(), this._cachedWorldViewProjectionMatrix);
}
// Connection points
for (var _i = 0, _a = this._sharedData.inputBlocks; _i < _a.length; _i++) {
var inputBlock = _a[_i];
inputBlock._transmitWorld(this._activeEffect, world, this._cachedWorldViewMatrix, this._cachedWorldViewProjectionMatrix);
}
};
/**
* Binds the submesh to this material by preparing the effect and shader to draw
* @param world defines the world transformation matrix
* @param mesh defines the mesh containing the submesh
* @param subMesh defines the submesh to bind the material to
*/
NodeMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
var scene = this.getScene();
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
// Matrices
this.bindOnlyWorldMatrix(world);
var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
if (mustRebind) {
var sharedData = this._sharedData;
if (effect && scene.getCachedEffect() !== effect) {
// Bindable blocks
for (var _i = 0, _a = sharedData.bindableBlocks; _i < _a.length; _i++) {
var block = _a[_i];
block.bind(effect, this, mesh, subMesh);
}
// Connection points
for (var _b = 0, _c = sharedData.inputBlocks; _b < _c.length; _b++) {
var inputBlock = _c[_b];
inputBlock._transmit(effect, scene);
}
}
}
this._afterBind(mesh, this._activeEffect);
};
/**
* Gets the active textures from the material
* @returns an array of textures
*/
NodeMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this._sharedData) {
activeTextures.push.apply(activeTextures, this._sharedData.textureBlocks.filter(function (tb) { return tb.texture; }).map(function (tb) { return tb.texture; }));
}
return activeTextures;
};
/**
* Gets the list of texture blocks
* @returns an array of texture blocks
*/
NodeMaterial.prototype.getTextureBlocks = function () {
if (!this._sharedData) {
return [];
}
return this._sharedData.textureBlocks;
};
/**
* Specifies if the material uses a texture
* @param texture defines the texture to check against the material
* @returns a boolean specifying if the material uses the texture
*/
NodeMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (!this._sharedData) {
return false;
}
for (var _i = 0, _a = this._sharedData.textureBlocks; _i < _a.length; _i++) {
var t = _a[_i];
if (t.texture === texture) {
return true;
}
}
return false;
};
/**
* Disposes the material
* @param forceDisposeEffect specifies if effects should be forcefully disposed
* @param forceDisposeTextures specifies if textures should be forcefully disposed
* @param notBoundToMesh specifies if the material that is being disposed is known to be not bound to any mesh
*/
NodeMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures, notBoundToMesh) {
if (forceDisposeTextures) {
for (var _i = 0, _a = this._sharedData.textureBlocks.filter(function (tb) { return tb.texture; }).map(function (tb) { return tb.texture; }); _i < _a.length; _i++) {
var texture = _a[_i];
texture.dispose();
}
}
for (var _b = 0, _c = this.attachedBlocks; _b < _c.length; _b++) {
var block = _c[_b];
block.dispose();
}
this.onBuildObservable.clear();
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures, notBoundToMesh);
};
/** Creates the node editor window. */
NodeMaterial.prototype._createNodeEditor = function () {
this.BJSNODEMATERIALEDITOR = this.BJSNODEMATERIALEDITOR || this._getGlobalNodeMaterialEditor();
this.BJSNODEMATERIALEDITOR.NodeEditor.Show({
nodeMaterial: this
});
};
/**
* Launch the node material editor
* @param config Define the configuration of the editor
* @return a promise fulfilled when the node editor is visible
*/
NodeMaterial.prototype.edit = function (config) {
var _this = this;
return new Promise(function (resolve, reject) {
if (typeof _this.BJSNODEMATERIALEDITOR == 'undefined') {
var editorUrl = config && config.editorURL ? config.editorURL : NodeMaterial.EditorURL;
// Load editor and add it to the DOM
_Misc_tools__WEBPACK_IMPORTED_MODULE_12__["Tools"].LoadScript(editorUrl, function () {
_this._createNodeEditor();
resolve();
});
}
else {
// Otherwise creates the editor
_this._createNodeEditor();
resolve();
}
});
};
/**
* Clear the current material
*/
NodeMaterial.prototype.clear = function () {
this._vertexOutputNodes = [];
this._fragmentOutputNodes = [];
this.attachedBlocks = [];
};
/**
* Clear the current material and set it to a default state
*/
NodeMaterial.prototype.setToDefault = function () {
this.clear();
this.editorData = null;
var positionInput = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("Position");
positionInput.setAsAttribute("position");
var worldInput = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("World");
worldInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.World);
var worldPos = new _Blocks_transformBlock__WEBPACK_IMPORTED_MODULE_13__["TransformBlock"]("WorldPos");
positionInput.connectTo(worldPos);
worldInput.connectTo(worldPos);
var viewProjectionInput = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("ViewProjection");
viewProjectionInput.setAsSystemValue(BABYLON.NodeMaterialSystemValues.ViewProjection);
var worldPosdMultipliedByViewProjection = new _Blocks_transformBlock__WEBPACK_IMPORTED_MODULE_13__["TransformBlock"]("WorldPos * ViewProjectionTransform");
worldPos.connectTo(worldPosdMultipliedByViewProjection);
viewProjectionInput.connectTo(worldPosdMultipliedByViewProjection);
var vertexOutput = new _Blocks_Vertex_vertexOutputBlock__WEBPACK_IMPORTED_MODULE_14__["VertexOutputBlock"]("VertexOutput");
worldPosdMultipliedByViewProjection.connectTo(vertexOutput);
// Pixel
var pixelColor = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("color");
pixelColor.value = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_4__["Color4"](0.8, 0.8, 0.8, 1);
var fragmentOutput = new _Blocks_Fragment_fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_15__["FragmentOutputBlock"]("FragmentOutput");
pixelColor.connectTo(fragmentOutput);
// Add to nodes
this.addOutputNode(vertexOutput);
this.addOutputNode(fragmentOutput);
this._mode = _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__["NodeMaterialModes"].Material;
};
/**
* Clear the current material and set it to a default state for post process
*/
NodeMaterial.prototype.setToDefaultPostProcess = function () {
this.clear();
this.editorData = null;
var position = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("Position");
position.setAsAttribute("position2d");
var const1 = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("Constant1");
const1.isConstant = true;
const1.value = 1;
var vmerger = new _Blocks_vectorMergerBlock__WEBPACK_IMPORTED_MODULE_28__["VectorMergerBlock"]("Position3D");
position.connectTo(vmerger);
const1.connectTo(vmerger, { input: "w" });
var vertexOutput = new _Blocks_Vertex_vertexOutputBlock__WEBPACK_IMPORTED_MODULE_14__["VertexOutputBlock"]("VertexOutput");
vmerger.connectTo(vertexOutput);
// Pixel
var scale = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("scale");
scale.visibleInInspector = true;
scale.value = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1, 1);
var uv0 = new _Blocks_remapBlock__WEBPACK_IMPORTED_MODULE_29__["RemapBlock"]("uv0");
position.connectTo(uv0);
var uv = new _Blocks_multiplyBlock__WEBPACK_IMPORTED_MODULE_30__["MultiplyBlock"]("uv");
uv0.connectTo(uv);
scale.connectTo(uv);
var currentScreen = new _Blocks_Dual_currentScreenBlock__WEBPACK_IMPORTED_MODULE_19__["CurrentScreenBlock"]("CurrentScreen");
uv.connectTo(currentScreen);
currentScreen.texture = new _Textures_texture__WEBPACK_IMPORTED_MODULE_32__["Texture"]("https://assets.babylonjs.com/nme/currentScreenPostProcess.png", this.getScene());
var fragmentOutput = new _Blocks_Fragment_fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_15__["FragmentOutputBlock"]("FragmentOutput");
currentScreen.connectTo(fragmentOutput, { output: "rgba" });
// Add to nodes
this.addOutputNode(vertexOutput);
this.addOutputNode(fragmentOutput);
this._mode = _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__["NodeMaterialModes"].PostProcess;
};
/**
* Clear the current material and set it to a default state for particle
*/
NodeMaterial.prototype.setToDefaultParticle = function () {
this.clear();
this.editorData = null;
// Pixel
var uv = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("uv");
uv.setAsAttribute("particle_uv");
var texture = new _Blocks_Particle_particleTextureBlock__WEBPACK_IMPORTED_MODULE_20__["ParticleTextureBlock"]("ParticleTexture");
uv.connectTo(texture);
var color = new _Blocks_Input_inputBlock__WEBPACK_IMPORTED_MODULE_16__["InputBlock"]("Color");
color.setAsAttribute("particle_color");
var multiply = new _Blocks_multiplyBlock__WEBPACK_IMPORTED_MODULE_30__["MultiplyBlock"]("Texture * Color");
texture.connectTo(multiply);
color.connectTo(multiply);
var rampGradient = new _Blocks_Particle_particleRampGradientBlock__WEBPACK_IMPORTED_MODULE_21__["ParticleRampGradientBlock"]("ParticleRampGradient");
multiply.connectTo(rampGradient);
var cSplitter = new _Blocks_colorSplitterBlock__WEBPACK_IMPORTED_MODULE_34__["ColorSplitterBlock"]("ColorSplitter");
color.connectTo(cSplitter);
var blendMultiply = new _Blocks_Particle_particleBlendMultiplyBlock__WEBPACK_IMPORTED_MODULE_22__["ParticleBlendMultiplyBlock"]("ParticleBlendMultiply");
rampGradient.connectTo(blendMultiply);
texture.connectTo(blendMultiply, { "output": "a" });
cSplitter.connectTo(blendMultiply, { "output": "a" });
var fragmentOutput = new _Blocks_Fragment_fragmentOutputBlock__WEBPACK_IMPORTED_MODULE_15__["FragmentOutputBlock"]("FragmentOutput");
blendMultiply.connectTo(fragmentOutput);
// Add to nodes
this.addOutputNode(fragmentOutput);
this._mode = _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__["NodeMaterialModes"].Particle;
};
/**
* Loads the current Node Material from a url pointing to a file save by the Node Material Editor
* @param url defines the url to load from
* @returns a promise that will fullfil when the material is fully loaded
*/
NodeMaterial.prototype.loadAsync = function (url) {
var _this = this;
return this.getScene()._loadFileAsync(url).then(function (data) {
var serializationObject = JSON.parse(data);
_this.loadFromSerialization(serializationObject, "");
});
};
NodeMaterial.prototype._gatherBlocks = function (rootNode, list) {
if (list.indexOf(rootNode) !== -1) {
return;
}
list.push(rootNode);
for (var _i = 0, _a = rootNode.inputs; _i < _a.length; _i++) {
var input = _a[_i];
var connectedPoint = input.connectedPoint;
if (connectedPoint) {
var block = connectedPoint.ownerBlock;
if (block !== rootNode) {
this._gatherBlocks(block, list);
}
}
}
};
/**
* Generate a string containing the code declaration required to create an equivalent of this material
* @returns a string
*/
NodeMaterial.prototype.generateCode = function () {
var alreadyDumped = [];
var vertexBlocks = [];
var uniqueNames = [];
// Gets active blocks
for (var _i = 0, _a = this._vertexOutputNodes; _i < _a.length; _i++) {
var outputNode = _a[_i];
this._gatherBlocks(outputNode, vertexBlocks);
}
var fragmentBlocks = [];
for (var _b = 0, _c = this._fragmentOutputNodes; _b < _c.length; _b++) {
var outputNode = _c[_b];
this._gatherBlocks(outputNode, fragmentBlocks);
}
// Generate vertex shader
var codeString = "var nodeMaterial = new BABYLON.NodeMaterial(\"" + (this.name || "node material") + "\");\r\n";
for (var _d = 0, vertexBlocks_1 = vertexBlocks; _d < vertexBlocks_1.length; _d++) {
var node = vertexBlocks_1[_d];
if (node.isInput && alreadyDumped.indexOf(node) === -1) {
codeString += node._dumpCode(uniqueNames, alreadyDumped);
}
}
// Generate fragment shader
for (var _e = 0, fragmentBlocks_1 = fragmentBlocks; _e < fragmentBlocks_1.length; _e++) {
var node = fragmentBlocks_1[_e];
if (node.isInput && alreadyDumped.indexOf(node) === -1) {
codeString += node._dumpCode(uniqueNames, alreadyDumped);
}
}
// Connections
alreadyDumped = [];
codeString += "\r\n// Connections\r\n";
for (var _f = 0, _g = this._vertexOutputNodes; _f < _g.length; _f++) {
var node = _g[_f];
codeString += node._dumpCodeForOutputConnections(alreadyDumped);
}
for (var _h = 0, _j = this._fragmentOutputNodes; _h < _j.length; _h++) {
var node = _j[_h];
codeString += node._dumpCodeForOutputConnections(alreadyDumped);
}
// Output nodes
codeString += "\r\n// Output nodes\r\n";
for (var _k = 0, _l = this._vertexOutputNodes; _k < _l.length; _k++) {
var node = _l[_k];
codeString += "nodeMaterial.addOutputNode(" + node._codeVariableName + ");\r\n";
}
for (var _m = 0, _o = this._fragmentOutputNodes; _m < _o.length; _m++) {
var node = _o[_m];
codeString += "nodeMaterial.addOutputNode(" + node._codeVariableName + ");\r\n";
}
codeString += "nodeMaterial.build();\r\n";
return codeString;
};
/**
* Serializes this material in a JSON representation
* @returns the serialized material object
*/
NodeMaterial.prototype.serialize = function (selectedBlocks) {
var serializationObject = selectedBlocks ? {} : _Misc_decorators__WEBPACK_IMPORTED_MODULE_18__["SerializationHelper"].Serialize(this);
serializationObject.editorData = JSON.parse(JSON.stringify(this.editorData)); // Copy
var blocks = [];
if (selectedBlocks) {
blocks = selectedBlocks;
}
else {
serializationObject.customType = "BABYLON.NodeMaterial";
serializationObject.outputNodes = [];
// Outputs
for (var _i = 0, _a = this._vertexOutputNodes; _i < _a.length; _i++) {
var outputNode = _a[_i];
this._gatherBlocks(outputNode, blocks);
serializationObject.outputNodes.push(outputNode.uniqueId);
}
for (var _b = 0, _c = this._fragmentOutputNodes; _b < _c.length; _b++) {
var outputNode = _c[_b];
this._gatherBlocks(outputNode, blocks);
if (serializationObject.outputNodes.indexOf(outputNode.uniqueId) === -1) {
serializationObject.outputNodes.push(outputNode.uniqueId);
}
}
}
// Blocks
serializationObject.blocks = [];
for (var _d = 0, blocks_1 = blocks; _d < blocks_1.length; _d++) {
var block = blocks_1[_d];
serializationObject.blocks.push(block.serialize());
}
if (!selectedBlocks) {
for (var _e = 0, _f = this.attachedBlocks; _e < _f.length; _e++) {
var block = _f[_e];
if (blocks.indexOf(block) !== -1) {
continue;
}
serializationObject.blocks.push(block.serialize());
}
}
return serializationObject;
};
NodeMaterial.prototype._restoreConnections = function (block, source, map) {
for (var _i = 0, _a = block.outputs; _i < _a.length; _i++) {
var outputPoint = _a[_i];
for (var _b = 0, _c = source.blocks; _b < _c.length; _b++) {
var candidate = _c[_b];
var target = map[candidate.id];
for (var _d = 0, _e = candidate.inputs; _d < _e.length; _d++) {
var input = _e[_d];
if (map[input.targetBlockId] === block && input.targetConnectionName === outputPoint.name) {
var inputPoint = target.getInputByName(input.inputName);
if (!inputPoint || inputPoint.isConnected) {
continue;
}
outputPoint.connectTo(inputPoint, true);
this._restoreConnections(target, source, map);
continue;
}
}
}
}
};
/**
* Clear the current graph and load a new one from a serialization object
* @param source defines the JSON representation of the material
* @param rootUrl defines the root URL to use to load textures and relative dependencies
* @param merge defines whether or not the source must be merged or replace the current content
*/
NodeMaterial.prototype.loadFromSerialization = function (source, rootUrl, merge) {
var _a;
if (rootUrl === void 0) { rootUrl = ""; }
if (merge === void 0) { merge = false; }
if (!merge) {
this.clear();
}
var map = {};
// Create blocks
for (var _i = 0, _b = source.blocks; _i < _b.length; _i++) {
var parsedBlock = _b[_i];
var blockType = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_17__["_TypeStore"].GetClass(parsedBlock.customType);
if (blockType) {
var block = new blockType();
block._deserialize(parsedBlock, this.getScene(), rootUrl);
map[parsedBlock.id] = block;
this.attachedBlocks.push(block);
}
}
// Connections - Starts with input blocks only (except if in "merge" mode where we scan all blocks)
for (var blockIndex = 0; blockIndex < source.blocks.length; blockIndex++) {
var parsedBlock_1 = source.blocks[blockIndex];
var block = map[parsedBlock_1.id];
if (block.inputs.length && !merge) {
continue;
}
this._restoreConnections(block, source, map);
}
// Outputs
if (source.outputNodes) {
for (var _c = 0, _d = source.outputNodes; _c < _d.length; _c++) {
var outputNodeId = _d[_c];
this.addOutputNode(map[outputNodeId]);
}
}
// UI related info
if (source.locations || source.editorData && source.editorData.locations) {
var locations = source.locations || source.editorData.locations;
for (var _e = 0, locations_1 = locations; _e < locations_1.length; _e++) {
var location = locations_1[_e];
if (map[location.blockId]) {
location.blockId = map[location.blockId].uniqueId;
}
}
if (merge && this.editorData && this.editorData.locations) {
locations.concat(this.editorData.locations);
}
if (source.locations) {
this.editorData = {
locations: locations
};
}
else {
this.editorData = source.editorData;
this.editorData.locations = locations;
}
var blockMap = [];
for (var key in map) {
blockMap[key] = map[key].uniqueId;
}
this.editorData.map = blockMap;
}
if (!merge) {
this._mode = (_a = source.mode) !== null && _a !== void 0 ? _a : _Enums_nodeMaterialModes__WEBPACK_IMPORTED_MODULE_31__["NodeMaterialModes"].Material;
}
};
/**
* Makes a duplicate of the current material.
* @param name - name to use for the new material.
*/
NodeMaterial.prototype.clone = function (name) {
var _this = this;
var serializationObject = this.serialize();
var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_18__["SerializationHelper"].Clone(function () { return new NodeMaterial(name, _this.getScene(), _this.options); }, this);
clone.id = name;
clone.name = name;
clone.loadFromSerialization(serializationObject);
clone.build();
return clone;
};
/**
* Creates a node material from parsed material data
* @param source defines the JSON representation of the material
* @param scene defines the hosting scene
* @param rootUrl defines the root URL to use to load textures and relative dependencies
* @returns a new node material
*/
NodeMaterial.Parse = function (source, scene, rootUrl) {
if (rootUrl === void 0) { rootUrl = ""; }
var nodeMaterial = _Misc_decorators__WEBPACK_IMPORTED_MODULE_18__["SerializationHelper"].Parse(function () { return new NodeMaterial(source.name, scene); }, source, scene, rootUrl);
nodeMaterial.loadFromSerialization(source, rootUrl);
nodeMaterial.build();
return nodeMaterial;
};
/**
* Creates a node material from a snippet saved in a remote file
* @param name defines the name of the material to create
* @param url defines the url to load from
* @param scene defines the hosting scene
* @returns a promise that will resolve to the new node material
*/
NodeMaterial.ParseFromFileAsync = function (name, url, scene) {
var material = new NodeMaterial(name, scene);
return new Promise(function (resolve, reject) {
return material.loadAsync(url).then(function () { return resolve(material); }).catch(reject);
});
};
/**
* Creates a node material from a snippet saved by the node material editor
* @param snippetId defines the snippet to load
* @param scene defines the hosting scene
* @param rootUrl defines the root URL to use to load textures and relative dependencies
* @param nodeMaterial defines a node material to update (instead of creating a new one)
* @returns a promise that will resolve to the new node material
*/
NodeMaterial.ParseFromSnippetAsync = function (snippetId, scene, rootUrl, nodeMaterial) {
var _this = this;
if (rootUrl === void 0) { rootUrl = ""; }
return new Promise(function (resolve, reject) {
var request = new _Misc_webRequest__WEBPACK_IMPORTED_MODULE_24__["WebRequest"]();
request.addEventListener("readystatechange", function () {
if (request.readyState == 4) {
if (request.status == 200) {
var snippet = JSON.parse(JSON.parse(request.responseText).jsonPayload);
var serializationObject = JSON.parse(snippet.nodeMaterial);
if (!nodeMaterial) {
nodeMaterial = _Misc_decorators__WEBPACK_IMPORTED_MODULE_18__["SerializationHelper"].Parse(function () { return new NodeMaterial(snippetId, scene); }, serializationObject, scene, rootUrl);
nodeMaterial.uniqueId = scene.getUniqueId();
}
nodeMaterial.loadFromSerialization(serializationObject);
nodeMaterial.snippetId = snippetId;
try {
nodeMaterial.build();
resolve(nodeMaterial);
}
catch (err) {
reject(err);
}
}
else {
reject("Unable to load the snippet " + snippetId);
}
}
});
request.open("GET", _this.SnippetUrl + "/" + snippetId.replace(/#/g, "/"));
request.send();
});
};
/**
* Creates a new node material set to default basic configuration
* @param name defines the name of the material
* @param scene defines the hosting scene
* @returns a new NodeMaterial
*/
NodeMaterial.CreateDefault = function (name, scene) {
var newMaterial = new NodeMaterial(name, scene);
newMaterial.setToDefault();
newMaterial.build();
return newMaterial;
};
NodeMaterial._BuildIdGenerator = 0;
/** Define the Url to load node editor script */
NodeMaterial.EditorURL = "https://unpkg.com/babylonjs-node-editor@" + _Engines_engine__WEBPACK_IMPORTED_MODULE_5__["Engine"].Version + "/babylon.nodeEditor.js";
/** Define the Url to load snippets */
NodeMaterial.SnippetUrl = "https://snippet.babylonjs.com";
/** Gets or sets a boolean indicating that node materials should not deserialize textures from json / snippet content */
NodeMaterial.IgnoreTexturesAtLoadTime = false;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_18__["serialize"])("mode")
], NodeMaterial.prototype, "_mode", void 0);
return NodeMaterial;
}(_pushMaterial__WEBPACK_IMPORTED_MODULE_1__["PushMaterial"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_17__["_TypeStore"].RegisteredTypes["BABYLON.NodeMaterial"] = NodeMaterial;
/***/ }),
/***/ "./Materials/Node/nodeMaterialBlock.ts":
/*!*********************************************!*\
!*** ./Materials/Node/nodeMaterialBlock.ts ***!
\*********************************************/
/*! exports provided: NodeMaterialBlock */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBlock", function() { return NodeMaterialBlock; });
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_uniqueIdGenerator__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/uniqueIdGenerator */ "./Misc/uniqueIdGenerator.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* Defines a block that can be used inside a node based material
*/
var NodeMaterialBlock = /** @class */ (function () {
/**
* Creates a new NodeMaterialBlock
* @param name defines the block name
* @param target defines the target of that block (Vertex by default)
* @param isFinalMerger defines a boolean indicating that this block is an end block (e.g. it is generating a system value). Default is false
* @param isInput defines a boolean indicating that this block is an input (e.g. it sends data to the shader). Default is false
*/
function NodeMaterialBlock(name, target, isFinalMerger, isInput) {
if (target === void 0) { target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex; }
if (isFinalMerger === void 0) { isFinalMerger = false; }
if (isInput === void 0) { isInput = false; }
this._isFinalMerger = false;
this._isInput = false;
this._name = "";
this._isUnique = false;
/** Gets or sets a boolean indicating that only one input can be connected at a time */
this.inputsAreExclusive = false;
/** @hidden */
this._codeVariableName = "";
/** @hidden */
this._inputs = new Array();
/** @hidden */
this._outputs = new Array();
/**
* Gets or sets the comments associated with this block
*/
this.comments = "";
this._target = target;
this._isFinalMerger = isFinalMerger;
this._isInput = isInput;
this._name = name;
this.uniqueId = _Misc_uniqueIdGenerator__WEBPACK_IMPORTED_MODULE_3__["UniqueIdGenerator"].UniqueId;
}
Object.defineProperty(NodeMaterialBlock.prototype, "name", {
/**
* Gets the name of the block
*/
get: function () {
return this._name;
},
/**
* Sets the name of the block. Will check if the name is valid.
*/
set: function (newName) {
if (!this.validateBlockName(newName)) {
return;
}
this._name = newName;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "isUnique", {
/**
* Gets a boolean indicating that this block can only be used once per NodeMaterial
*/
get: function () {
return this._isUnique;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "isFinalMerger", {
/**
* Gets a boolean indicating that this block is an end block (e.g. it is generating a system value)
*/
get: function () {
return this._isFinalMerger;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "isInput", {
/**
* Gets a boolean indicating that this block is an input (e.g. it sends data to the shader)
*/
get: function () {
return this._isInput;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "buildId", {
/**
* Gets or sets the build Id
*/
get: function () {
return this._buildId;
},
set: function (value) {
this._buildId = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "target", {
/**
* Gets or sets the target of the block
*/
get: function () {
return this._target;
},
set: function (value) {
if ((this._target & value) !== 0) {
return;
}
this._target = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "inputs", {
/**
* Gets the list of input points
*/
get: function () {
return this._inputs;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialBlock.prototype, "outputs", {
/** Gets the list of output points */
get: function () {
return this._outputs;
},
enumerable: false,
configurable: true
});
/**
* Find an input by its name
* @param name defines the name of the input to look for
* @returns the input or null if not found
*/
NodeMaterialBlock.prototype.getInputByName = function (name) {
var filter = this._inputs.filter(function (e) { return e.name === name; });
if (filter.length) {
return filter[0];
}
return null;
};
/**
* Find an output by its name
* @param name defines the name of the outputto look for
* @returns the output or null if not found
*/
NodeMaterialBlock.prototype.getOutputByName = function (name) {
var filter = this._outputs.filter(function (e) { return e.name === name; });
if (filter.length) {
return filter[0];
}
return null;
};
/**
* Initialize the block and prepare the context for build
* @param state defines the state that will be used for the build
*/
NodeMaterialBlock.prototype.initialize = function (state) {
// Do nothing
};
/**
* Bind data to effect. Will only be called for blocks with isBindable === true
* @param effect defines the effect to bind data to
* @param nodeMaterial defines the hosting NodeMaterial
* @param mesh defines the mesh that will be rendered
* @param subMesh defines the submesh that will be rendered
*/
NodeMaterialBlock.prototype.bind = function (effect, nodeMaterial, mesh, subMesh) {
// Do nothing
};
NodeMaterialBlock.prototype._declareOutput = function (output, state) {
return state._getGLType(output.type) + " " + output.associatedVariableName;
};
NodeMaterialBlock.prototype._writeVariable = function (currentPoint) {
var connectionPoint = currentPoint.connectedPoint;
if (connectionPoint) {
return "" + currentPoint.associatedVariableName;
}
return "0.";
};
NodeMaterialBlock.prototype._writeFloat = function (value) {
var stringVersion = value.toString();
if (stringVersion.indexOf(".") === -1) {
stringVersion += ".0";
}
return "" + stringVersion;
};
/**
* Gets the current class name e.g. "NodeMaterialBlock"
* @returns the class name
*/
NodeMaterialBlock.prototype.getClassName = function () {
return "NodeMaterialBlock";
};
/**
* Register a new input. Must be called inside a block constructor
* @param name defines the connection point name
* @param type defines the connection point type
* @param isOptional defines a boolean indicating that this input can be omitted
* @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)
* @param point an already created connection point. If not provided, create a new one
* @returns the current block
*/
NodeMaterialBlock.prototype.registerInput = function (name, type, isOptional, target, point) {
if (isOptional === void 0) { isOptional = false; }
point = point !== null && point !== void 0 ? point : new _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPoint"](name, this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPointDirection"].Input);
point.type = type;
point.isOptional = isOptional;
if (target) {
point.target = target;
}
this._inputs.push(point);
return this;
};
/**
* Register a new output. Must be called inside a block constructor
* @param name defines the connection point name
* @param type defines the connection point type
* @param target defines the target to use to limit the connection point (will be VertexAndFragment by default)
* @param point an already created connection point. If not provided, create a new one
* @returns the current block
*/
NodeMaterialBlock.prototype.registerOutput = function (name, type, target, point) {
point = point !== null && point !== void 0 ? point : new _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPoint"](name, this, _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPointDirection"].Output);
point.type = type;
if (target) {
point.target = target;
}
this._outputs.push(point);
return this;
};
/**
* Will return the first available input e.g. the first one which is not an uniform or an attribute
* @param forOutput defines an optional connection point to check compatibility with
* @returns the first available input or null
*/
NodeMaterialBlock.prototype.getFirstAvailableInput = function (forOutput) {
if (forOutput === void 0) { forOutput = null; }
for (var _i = 0, _a = this._inputs; _i < _a.length; _i++) {
var input = _a[_i];
if (!input.connectedPoint) {
if (!forOutput || (forOutput.type === input.type) || (input.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].AutoDetect)) {
return input;
}
}
}
return null;
};
/**
* Will return the first available output e.g. the first one which is not yet connected and not a varying
* @param forBlock defines an optional block to check compatibility with
* @returns the first available input or null
*/
NodeMaterialBlock.prototype.getFirstAvailableOutput = function (forBlock) {
if (forBlock === void 0) { forBlock = null; }
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (!forBlock || !forBlock.target || forBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Neutral || (forBlock.target & output.target) !== 0) {
return output;
}
}
return null;
};
/**
* Gets the sibling of the given output
* @param current defines the current output
* @returns the next output in the list or null
*/
NodeMaterialBlock.prototype.getSiblingOutput = function (current) {
var index = this._outputs.indexOf(current);
if (index === -1 || index >= this._outputs.length) {
return null;
}
return this._outputs[index + 1];
};
/**
* Connect current block with another block
* @param other defines the block to connect with
* @param options define the various options to help pick the right connections
* @returns the current block
*/
NodeMaterialBlock.prototype.connectTo = function (other, options) {
if (this._outputs.length === 0) {
return;
}
var output = options && options.output ? this.getOutputByName(options.output) : this.getFirstAvailableOutput(other);
var notFound = true;
while (notFound) {
var input = options && options.input ? other.getInputByName(options.input) : other.getFirstAvailableInput(output);
if (output && input && output.canConnectTo(input)) {
output.connectTo(input);
notFound = false;
}
else if (!output) {
throw "Unable to find a compatible match";
}
else {
output = this.getSiblingOutput(output);
}
}
return this;
};
NodeMaterialBlock.prototype._buildBlock = function (state) {
// Empty. Must be defined by child nodes
};
/**
* Add uniforms, samplers and uniform buffers at compilation time
* @param state defines the state to update
* @param nodeMaterial defines the node material requesting the update
* @param defines defines the material defines to update
* @param uniformBuffers defines the list of uniform buffer names
*/
NodeMaterialBlock.prototype.updateUniformsAndSamples = function (state, nodeMaterial, defines, uniformBuffers) {
// Do nothing
};
/**
* Add potential fallbacks if shader compilation fails
* @param mesh defines the mesh to be rendered
* @param fallbacks defines the current prioritized list of fallbacks
*/
NodeMaterialBlock.prototype.provideFallbacks = function (mesh, fallbacks) {
// Do nothing
};
/**
* Initialize defines for shader compilation
* @param mesh defines the mesh to be rendered
* @param nodeMaterial defines the node material requesting the update
* @param defines defines the material defines to update
* @param useInstances specifies that instances should be used
*/
NodeMaterialBlock.prototype.initializeDefines = function (mesh, nodeMaterial, defines, useInstances) {
if (useInstances === void 0) { useInstances = false; }
};
/**
* Update defines for shader compilation
* @param mesh defines the mesh to be rendered
* @param nodeMaterial defines the node material requesting the update
* @param defines defines the material defines to update
* @param useInstances specifies that instances should be used
* @param subMesh defines which submesh to render
*/
NodeMaterialBlock.prototype.prepareDefines = function (mesh, nodeMaterial, defines, useInstances, subMesh) {
if (useInstances === void 0) { useInstances = false; }
// Do nothing
};
/**
* Lets the block try to connect some inputs automatically
* @param material defines the hosting NodeMaterial
*/
NodeMaterialBlock.prototype.autoConfigure = function (material) {
// Do nothing
};
/**
* Function called when a block is declared as repeatable content generator
* @param vertexShaderState defines the current compilation state for the vertex shader
* @param fragmentShaderState defines the current compilation state for the fragment shader
* @param mesh defines the mesh to be rendered
* @param defines defines the material defines to update
*/
NodeMaterialBlock.prototype.replaceRepeatableContent = function (vertexShaderState, fragmentShaderState, mesh, defines) {
// Do nothing
};
/**
* Checks if the block is ready
* @param mesh defines the mesh to be rendered
* @param nodeMaterial defines the node material requesting the update
* @param defines defines the material defines to update
* @param useInstances specifies that instances should be used
* @returns true if the block is ready
*/
NodeMaterialBlock.prototype.isReady = function (mesh, nodeMaterial, defines, useInstances) {
if (useInstances === void 0) { useInstances = false; }
return true;
};
NodeMaterialBlock.prototype._linkConnectionTypes = function (inputIndex0, inputIndex1) {
this._inputs[inputIndex0]._linkedConnectionSource = this._inputs[inputIndex1];
this._inputs[inputIndex1]._linkedConnectionSource = this._inputs[inputIndex0];
};
NodeMaterialBlock.prototype._processBuild = function (block, state, input, activeBlocks) {
block.build(state, activeBlocks);
var localBlockIsFragment = (state._vertexState != null);
var otherBlockWasGeneratedInVertexShader = block._buildTarget === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex && block.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].VertexAndFragment;
if (localBlockIsFragment && (((block.target & block._buildTarget) === 0) ||
((block.target & input.target) === 0) ||
(this.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].VertexAndFragment && otherBlockWasGeneratedInVertexShader))) { // context switch! We need a varying
if ((!block.isInput && state.target !== block._buildTarget) // block was already emitted by vertex shader
|| (block.isInput && block.isAttribute && !block._noContextSwitch) // block is an attribute
) {
var connectedPoint = input.connectedPoint;
if (state._vertexState._emitVaryingFromString("v_" + connectedPoint.associatedVariableName, state._getGLType(connectedPoint.type))) {
state._vertexState.compilationString += "v_" + connectedPoint.associatedVariableName + " = " + connectedPoint.associatedVariableName + ";\r\n";
}
input.associatedVariableName = "v_" + connectedPoint.associatedVariableName;
input._enforceAssociatedVariableName = true;
}
}
};
/**
* Validates the new name for the block node.
* @param newName the new name to be given to the node.
* @returns false if the name is a reserve word, else true.
*/
NodeMaterialBlock.prototype.validateBlockName = function (newName) {
var reservedNames = [
"position",
"normal",
"tangent",
"particle_positionw",
"uv",
"uv2",
"position2d",
"particle_uv",
"matricesIndices",
"matricesWeights",
"world0",
"world1",
"world2",
"world3",
"particle_color",
"particle_texturemask"
];
for (var _i = 0, reservedNames_1 = reservedNames; _i < reservedNames_1.length; _i++) {
var reservedName = reservedNames_1[_i];
if (newName === reservedName) {
return false;
}
}
return true;
};
/**
* Compile the current node and generate the shader code
* @param state defines the current compilation state (uniforms, samplers, current string)
* @param activeBlocks defines the list of active blocks (i.e. blocks to compile)
* @returns true if already built
*/
NodeMaterialBlock.prototype.build = function (state, activeBlocks) {
if (this._buildId === state.sharedData.buildId) {
return true;
}
if (!this.isInput) {
/** Prepare outputs */
for (var _i = 0, _a = this._outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (!output.associatedVariableName) {
output.associatedVariableName = state._getFreeVariableName(output.name);
}
}
}
// Check if "parent" blocks are compiled
for (var _b = 0, _c = this._inputs; _b < _c.length; _b++) {
var input = _c[_b];
if (!input.connectedPoint) {
if (!input.isOptional) { // Emit a warning
state.sharedData.checks.notConnectedNonOptionalInputs.push(input);
}
continue;
}
if (this.target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Neutral) {
if ((input.target & this.target) === 0) {
continue;
}
if ((input.target & state.target) === 0) {
continue;
}
}
var block = input.connectedPoint.ownerBlock;
if (block && block !== this) {
this._processBuild(block, state, input, activeBlocks);
}
}
if (this._buildId === state.sharedData.buildId) {
return true; // Need to check again as inputs can be connected multiple time to this endpoint
}
// Logs
if (state.sharedData.verbose) {
console.log((state.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex ? "Vertex shader" : "Fragment shader") + ": Building " + this.name + " [" + this.getClassName() + "]");
}
// Checks final outputs
if (this.isFinalMerger) {
switch (state.target) {
case _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Vertex:
state.sharedData.checks.emitVertex = true;
break;
case _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_2__["NodeMaterialBlockTargets"].Fragment:
state.sharedData.checks.emitFragment = true;
break;
}
}
if (!this.isInput && state.sharedData.emitComments) {
state.compilationString += "\r\n//" + this.name + "\r\n";
}
this._buildBlock(state);
this._buildId = state.sharedData.buildId;
this._buildTarget = state.target;
// Compile connected blocks
for (var _d = 0, _e = this._outputs; _d < _e.length; _d++) {
var output = _e[_d];
if ((output.target & state.target) === 0) {
continue;
}
for (var _f = 0, _g = output.endpoints; _f < _g.length; _f++) {
var endpoint = _g[_f];
var block = endpoint.ownerBlock;
if (block && (block.target & state.target) !== 0 && activeBlocks.indexOf(block) !== -1) {
this._processBuild(block, state, endpoint, activeBlocks);
}
}
}
return false;
};
NodeMaterialBlock.prototype._inputRename = function (name) {
return name;
};
NodeMaterialBlock.prototype._outputRename = function (name) {
return name;
};
NodeMaterialBlock.prototype._dumpPropertiesCode = function () {
return "";
};
/** @hidden */
NodeMaterialBlock.prototype._dumpCode = function (uniqueNames, alreadyDumped) {
alreadyDumped.push(this);
var codeString;
// Get unique name
var nameAsVariableName = this.name.replace(/[^A-Za-z_]+/g, "");
this._codeVariableName = nameAsVariableName || this.getClassName() + "_" + this.uniqueId;
if (uniqueNames.indexOf(this._codeVariableName) !== -1) {
var index = 0;
do {
index++;
this._codeVariableName = nameAsVariableName + index;
} while (uniqueNames.indexOf(this._codeVariableName) !== -1);
}
uniqueNames.push(this._codeVariableName);
// Declaration
codeString = "\r\n// " + this.getClassName() + "\r\n";
if (this.comments) {
codeString += "// " + this.comments + "\r\n";
}
codeString += "var " + this._codeVariableName + " = new BABYLON." + this.getClassName() + "(\"" + this.name + "\");\r\n";
// Properties
codeString += this._dumpPropertiesCode();
// Inputs
for (var _i = 0, _a = this.inputs; _i < _a.length; _i++) {
var input = _a[_i];
if (!input.isConnected) {
continue;
}
var connectedOutput = input.connectedPoint;
var connectedBlock = connectedOutput.ownerBlock;
if (alreadyDumped.indexOf(connectedBlock) === -1) {
codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
}
}
// Outputs
for (var _b = 0, _c = this.outputs; _b < _c.length; _b++) {
var output = _c[_b];
if (!output.hasEndpoints) {
continue;
}
for (var _d = 0, _e = output.endpoints; _d < _e.length; _d++) {
var endpoint = _e[_d];
var connectedBlock = endpoint.ownerBlock;
if (connectedBlock && alreadyDumped.indexOf(connectedBlock) === -1) {
codeString += connectedBlock._dumpCode(uniqueNames, alreadyDumped);
}
}
}
return codeString;
};
/** @hidden */
NodeMaterialBlock.prototype._dumpCodeForOutputConnections = function (alreadyDumped) {
var codeString = "";
if (alreadyDumped.indexOf(this) !== -1) {
return codeString;
}
alreadyDumped.push(this);
for (var _i = 0, _a = this.inputs; _i < _a.length; _i++) {
var input = _a[_i];
if (!input.isConnected) {
continue;
}
var connectedOutput = input.connectedPoint;
var connectedBlock = connectedOutput.ownerBlock;
codeString += connectedBlock._dumpCodeForOutputConnections(alreadyDumped);
codeString += connectedBlock._codeVariableName + "." + connectedBlock._outputRename(connectedOutput.name) + ".connectTo(" + this._codeVariableName + "." + this._inputRename(input.name) + ");\r\n";
}
return codeString;
};
/**
* Clone the current block to a new identical block
* @param scene defines the hosting scene
* @param rootUrl defines the root URL to use to load textures and relative dependencies
* @returns a copy of the current block
*/
NodeMaterialBlock.prototype.clone = function (scene, rootUrl) {
if (rootUrl === void 0) { rootUrl = ""; }
var serializationObject = this.serialize();
var blockType = _Misc_typeStore__WEBPACK_IMPORTED_MODULE_4__["_TypeStore"].GetClass(serializationObject.customType);
if (blockType) {
var block = new blockType();
block._deserialize(serializationObject, scene, rootUrl);
return block;
}
return null;
};
/**
* Serializes this block in a JSON representation
* @returns the serialized block object
*/
NodeMaterialBlock.prototype.serialize = function () {
var serializationObject = {};
serializationObject.customType = "BABYLON." + this.getClassName();
serializationObject.id = this.uniqueId;
serializationObject.name = this.name;
serializationObject.comments = this.comments;
serializationObject.inputs = [];
serializationObject.outputs = [];
for (var _i = 0, _a = this.inputs; _i < _a.length; _i++) {
var input = _a[_i];
serializationObject.inputs.push(input.serialize());
}
for (var _b = 0, _c = this.outputs; _b < _c.length; _b++) {
var output = _c[_b];
serializationObject.outputs.push(output.serialize(false));
}
return serializationObject;
};
/** @hidden */
NodeMaterialBlock.prototype._deserialize = function (serializationObject, scene, rootUrl) {
this.name = serializationObject.name;
this.comments = serializationObject.comments;
this._deserializePortDisplayNamesAndExposedOnFrame(serializationObject);
};
NodeMaterialBlock.prototype._deserializePortDisplayNamesAndExposedOnFrame = function (serializationObject) {
var _this = this;
var serializedInputs = serializationObject.inputs;
var serializedOutputs = serializationObject.outputs;
if (serializedInputs) {
serializedInputs.forEach(function (port, i) {
if (port.displayName) {
_this.inputs[i].displayName = port.displayName;
}
if (port.isExposedOnFrame) {
_this.inputs[i].isExposedOnFrame = port.isExposedOnFrame;
}
});
}
if (serializedOutputs) {
serializedOutputs.forEach(function (port, i) {
if (port.displayName) {
_this.outputs[i].displayName = port.displayName;
}
if (port.isExposedOnFrame) {
_this.outputs[i].isExposedOnFrame = port.isExposedOnFrame;
}
});
}
};
/**
* Release resources
*/
NodeMaterialBlock.prototype.dispose = function () {
for (var _i = 0, _a = this.inputs; _i < _a.length; _i++) {
var input = _a[_i];
input.dispose();
}
for (var _b = 0, _c = this.outputs; _b < _c.length; _b++) {
var output = _c[_b];
output.dispose();
}
};
return NodeMaterialBlock;
}());
/***/ }),
/***/ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts":
/*!************************************************************!*\
!*** ./Materials/Node/nodeMaterialBlockConnectionPoint.ts ***!
\************************************************************/
/*! exports provided: NodeMaterialConnectionPointCompatibilityStates, NodeMaterialConnectionPointDirection, NodeMaterialConnectionPoint */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointCompatibilityStates", function() { return NodeMaterialConnectionPointCompatibilityStates; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointDirection", function() { return NodeMaterialConnectionPointDirection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPoint", function() { return NodeMaterialConnectionPoint; });
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _Misc_observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/observable */ "./Misc/observable.ts");
/**
* Enum used to define the compatibility state between two connection points
*/
var NodeMaterialConnectionPointCompatibilityStates;
(function (NodeMaterialConnectionPointCompatibilityStates) {
/** Points are compatibles */
NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["Compatible"] = 0] = "Compatible";
/** Points are incompatible because of their types */
NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["TypeIncompatible"] = 1] = "TypeIncompatible";
/** Points are incompatible because of their targets (vertex vs fragment) */
NodeMaterialConnectionPointCompatibilityStates[NodeMaterialConnectionPointCompatibilityStates["TargetIncompatible"] = 2] = "TargetIncompatible";
})(NodeMaterialConnectionPointCompatibilityStates || (NodeMaterialConnectionPointCompatibilityStates = {}));
/**
* Defines the direction of a connection point
*/
var NodeMaterialConnectionPointDirection;
(function (NodeMaterialConnectionPointDirection) {
/** Input */
NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection["Input"] = 0] = "Input";
/** Output */
NodeMaterialConnectionPointDirection[NodeMaterialConnectionPointDirection["Output"] = 1] = "Output";
})(NodeMaterialConnectionPointDirection || (NodeMaterialConnectionPointDirection = {}));
/**
* Defines a connection point for a block
*/
var NodeMaterialConnectionPoint = /** @class */ (function () {
/**
* Creates a new connection point
* @param name defines the connection point name
* @param ownerBlock defines the block hosting this connection point
* @param direction defines the direction of the connection point
*/
function NodeMaterialConnectionPoint(name, ownerBlock, direction) {
/** @hidden */
this._connectedPoint = null;
this._endpoints = new Array();
/** @hidden */
this._typeConnectionSource = null;
/** @hidden */
this._linkedConnectionSource = null;
this._type = _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Float;
/** @hidden */
this._enforceAssociatedVariableName = false;
/** Indicates that this connection point needs dual validation before being connected to another point */
this.needDualDirectionValidation = false;
/**
* Gets or sets the additional types supported by this connection point
*/
this.acceptedConnectionPointTypes = new Array();
/**
* Gets or sets the additional types excluded by this connection point
*/
this.excludedConnectionPointTypes = new Array();
/**
* Observable triggered when this point is connected
*/
this.onConnectionObservable = new _Misc_observable__WEBPACK_IMPORTED_MODULE_2__["Observable"]();
/**
* Gets or sets a boolean indicating that this connection point is exposed on a frame
*/
this.isExposedOnFrame = false;
/** @hidden */
this._prioritizeVertex = false;
this._target = _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].VertexAndFragment;
this._ownerBlock = ownerBlock;
this.name = name;
this._direction = direction;
}
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "direction", {
/** Gets the direction of the point */
get: function () {
return this._direction;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "associatedVariableName", {
/**
* Gets or sets the associated variable name in the shader
*/
get: function () {
if (this._ownerBlock.isInput) {
return this._ownerBlock.associatedVariableName;
}
if ((!this._enforceAssociatedVariableName || !this._associatedVariableName) && this._connectedPoint) {
return this._connectedPoint.associatedVariableName;
}
return this._associatedVariableName;
},
set: function (value) {
this._associatedVariableName = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "innerType", {
/** Get the inner type (ie AutoDetect for instance instead of the inferred one) */
get: function () {
if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) {
return this.type;
}
return this._type;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "type", {
/**
* Gets or sets the connection point type (default is float)
*/
get: function () {
if (this._type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].AutoDetect) {
if (this._ownerBlock.isInput) {
return this._ownerBlock.type;
}
if (this._connectedPoint) {
return this._connectedPoint.type;
}
if (this._linkedConnectionSource && this._linkedConnectionSource.isConnected) {
return this._linkedConnectionSource.type;
}
}
if (this._type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].BasedOnInput && this._typeConnectionSource) {
return this._typeConnectionSource.type;
}
return this._type;
},
set: function (value) {
this._type = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "target", {
/** Gets or sets the target of that connection point */
get: function () {
if (!this._prioritizeVertex || !this._ownerBlock) {
return this._target;
}
if (this._target !== _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].VertexAndFragment) {
return this._target;
}
if (this._ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment) {
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment;
}
return _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex;
},
set: function (value) {
this._target = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isConnected", {
/**
* Gets a boolean indicating that the current point is connected to another NodeMaterialBlock
*/
get: function () {
return this.connectedPoint !== null || this.hasEndpoints;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isConnectedToInputBlock", {
/**
* Gets a boolean indicating that the current point is connected to an input block
*/
get: function () {
return this.connectedPoint !== null && this.connectedPoint.ownerBlock.isInput;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "connectInputBlock", {
/**
* Gets a the connected input block (if any)
*/
get: function () {
if (!this.isConnectedToInputBlock) {
return null;
}
return this.connectedPoint.ownerBlock;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "connectedPoint", {
/** Get the other side of the connection (if any) */
get: function () {
return this._connectedPoint;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "ownerBlock", {
/** Get the block that owns this connection point */
get: function () {
return this._ownerBlock;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "sourceBlock", {
/** Get the block connected on the other side of this connection (if any) */
get: function () {
if (!this._connectedPoint) {
return null;
}
return this._connectedPoint.ownerBlock;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "connectedBlocks", {
/** Get the block connected on the endpoints of this connection (if any) */
get: function () {
if (this._endpoints.length === 0) {
return [];
}
return this._endpoints.map(function (e) { return e.ownerBlock; });
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "endpoints", {
/** Gets the list of connected endpoints */
get: function () {
return this._endpoints;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "hasEndpoints", {
/** Gets a boolean indicating if that output point is connected to at least one input */
get: function () {
return this._endpoints && this._endpoints.length > 0;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isConnectedInVertexShader", {
/** Gets a boolean indicating that this connection will be used in the vertex shader */
get: function () {
if (this.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex) {
return true;
}
if (!this.hasEndpoints) {
return false;
}
for (var _i = 0, _a = this._endpoints; _i < _a.length; _i++) {
var endpoint = _a[_i];
if (endpoint.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex) {
return true;
}
if (endpoint.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex) {
return true;
}
if (endpoint.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Neutral || endpoint.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].VertexAndFragment) {
if (endpoint.ownerBlock.outputs.some(function (o) { return o.isConnectedInVertexShader; })) {
return true;
}
}
}
return false;
},
enumerable: false,
configurable: true
});
Object.defineProperty(NodeMaterialConnectionPoint.prototype, "isConnectedInFragmentShader", {
/** Gets a boolean indicating that this connection will be used in the fragment shader */
get: function () {
if (this.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment) {
return true;
}
if (!this.hasEndpoints) {
return false;
}
for (var _i = 0, _a = this._endpoints; _i < _a.length; _i++) {
var endpoint = _a[_i];
if (endpoint.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment) {
return true;
}
if (endpoint.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Neutral || endpoint.ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].VertexAndFragment) {
if (endpoint.ownerBlock.outputs.some(function (o) { return o.isConnectedInFragmentShader; })) {
return true;
}
}
}
return false;
},
enumerable: false,
configurable: true
});
/**
* Creates a block suitable to be used as an input for this input point.
* If null is returned, a block based on the point type will be created.
* @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input
*/
NodeMaterialConnectionPoint.prototype.createCustomInputBlock = function () {
return null;
};
/**
* Gets the current class name e.g. "NodeMaterialConnectionPoint"
* @returns the class name
*/
NodeMaterialConnectionPoint.prototype.getClassName = function () {
return "NodeMaterialConnectionPoint";
};
/**
* Gets a boolean indicating if the current point can be connected to another point
* @param connectionPoint defines the other connection point
* @returns a boolean
*/
NodeMaterialConnectionPoint.prototype.canConnectTo = function (connectionPoint) {
return this.checkCompatibilityState(connectionPoint) === NodeMaterialConnectionPointCompatibilityStates.Compatible;
};
/**
* Gets a number indicating if the current point can be connected to another point
* @param connectionPoint defines the other connection point
* @returns a number defining the compatibility state
*/
NodeMaterialConnectionPoint.prototype.checkCompatibilityState = function (connectionPoint) {
var ownerBlock = this._ownerBlock;
if (ownerBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment) {
// Let's check we are not going reverse
var otherBlock = connectionPoint.ownerBlock;
if (otherBlock.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Vertex) {
return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;
}
for (var _i = 0, _a = otherBlock.outputs; _i < _a.length; _i++) {
var output = _a[_i];
if (output.isConnectedInVertexShader) {
return NodeMaterialConnectionPointCompatibilityStates.TargetIncompatible;
}
}
}
if (this.type !== connectionPoint.type && connectionPoint.innerType !== _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].AutoDetect) {
// Equivalents
switch (this.type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3: {
if (connectionPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3) {
return NodeMaterialConnectionPointCompatibilityStates.Compatible;
}
break;
}
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4: {
if (connectionPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color4) {
return NodeMaterialConnectionPointCompatibilityStates.Compatible;
}
break;
}
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3: {
if (connectionPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3) {
return NodeMaterialConnectionPointCompatibilityStates.Compatible;
}
break;
}
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color4: {
if (connectionPoint.type === _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4) {
return NodeMaterialConnectionPointCompatibilityStates.Compatible;
}
break;
}
}
// Accepted types
if (connectionPoint.acceptedConnectionPointTypes && connectionPoint.acceptedConnectionPointTypes.indexOf(this.type) !== -1) {
return NodeMaterialConnectionPointCompatibilityStates.Compatible;
}
else {
return NodeMaterialConnectionPointCompatibilityStates.TypeIncompatible;
}
}
// Excluded
if ((connectionPoint.excludedConnectionPointTypes && connectionPoint.excludedConnectionPointTypes.indexOf(this.type) !== -1)) {
return 1;
}
return NodeMaterialConnectionPointCompatibilityStates.Compatible;
};
/**
* Connect this point to another connection point
* @param connectionPoint defines the other connection point
* @param ignoreConstraints defines if the system will ignore connection type constraints (default is false)
* @returns the current connection point
*/
NodeMaterialConnectionPoint.prototype.connectTo = function (connectionPoint, ignoreConstraints) {
if (ignoreConstraints === void 0) { ignoreConstraints = false; }
if (!ignoreConstraints && !this.canConnectTo(connectionPoint)) {
throw "Cannot connect these two connectors.";
}
this._endpoints.push(connectionPoint);
connectionPoint._connectedPoint = this;
this._enforceAssociatedVariableName = false;
this.onConnectionObservable.notifyObservers(connectionPoint);
connectionPoint.onConnectionObservable.notifyObservers(this);
return this;
};
/**
* Disconnect this point from one of his endpoint
* @param endpoint defines the other connection point
* @returns the current connection point
*/
NodeMaterialConnectionPoint.prototype.disconnectFrom = function (endpoint) {
var index = this._endpoints.indexOf(endpoint);
if (index === -1) {
return this;
}
this._endpoints.splice(index, 1);
endpoint._connectedPoint = null;
this._enforceAssociatedVariableName = false;
endpoint._enforceAssociatedVariableName = false;
return this;
};
/**
* Serializes this point in a JSON representation
* @param isInput defines if the connection point is an input (default is true)
* @returns the serialized point object
*/
NodeMaterialConnectionPoint.prototype.serialize = function (isInput) {
if (isInput === void 0) { isInput = true; }
var serializationObject = {};
serializationObject.name = this.name;
serializationObject.displayName = this.displayName;
if (isInput && this.connectedPoint) {
serializationObject.inputName = this.name;
serializationObject.targetBlockId = this.connectedPoint.ownerBlock.uniqueId;
serializationObject.targetConnectionName = this.connectedPoint.name;
}
if (this.isExposedOnFrame) {
serializationObject.isExposedOnFrame = this.isExposedOnFrame;
}
return serializationObject;
};
/**
* Release resources
*/
NodeMaterialConnectionPoint.prototype.dispose = function () {
this.onConnectionObservable.clear();
};
return NodeMaterialConnectionPoint;
}());
/***/ }),
/***/ "./Materials/Node/nodeMaterialBuildState.ts":
/*!**************************************************!*\
!*** ./Materials/Node/nodeMaterialBuildState.ts ***!
\**************************************************/
/*! exports provided: NodeMaterialBuildState */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBuildState", function() { return NodeMaterialBuildState; });
/* harmony import */ var _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockConnectionPointTypes */ "./Materials/Node/Enums/nodeMaterialBlockConnectionPointTypes.ts");
/* harmony import */ var _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Enums/nodeMaterialBlockTargets */ "./Materials/Node/Enums/nodeMaterialBlockTargets.ts");
/* harmony import */ var _effect__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../effect */ "./Materials/effect.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/stringTools */ "./Misc/stringTools.ts");
/**
* Class used to store node based material build state
*/
var NodeMaterialBuildState = /** @class */ (function () {
function NodeMaterialBuildState() {
/** Gets or sets a boolean indicating if the current state can emit uniform buffers */
this.supportUniformBuffers = false;
/**
* Gets the list of emitted attributes
*/
this.attributes = new Array();
/**
* Gets the list of emitted uniforms
*/
this.uniforms = new Array();
/**
* Gets the list of emitted constants
*/
this.constants = new Array();
/**
* Gets the list of emitted samplers
*/
this.samplers = new Array();
/**
* Gets the list of emitted functions
*/
this.functions = {};
/**
* Gets the list of emitted extensions
*/
this.extensions = {};
/**
* Gets the list of emitted counters
*/
this.counters = {};
/** @hidden */
this._attributeDeclaration = "";
/** @hidden */
this._uniformDeclaration = "";
/** @hidden */
this._constantDeclaration = "";
/** @hidden */
this._samplerDeclaration = "";
/** @hidden */
this._varyingTransfer = "";
/** @hidden */
this._injectAtEnd = "";
this._repeatableContentAnchorIndex = 0;
/** @hidden */
this._builtCompilationString = "";
/**
* Gets the emitted compilation strings
*/
this.compilationString = "";
}
/**
* Finalize the compilation strings
* @param state defines the current compilation state
*/
NodeMaterialBuildState.prototype.finalize = function (state) {
var emitComments = state.sharedData.emitComments;
var isFragmentMode = (this.target === _Enums_nodeMaterialBlockTargets__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialBlockTargets"].Fragment);
this.compilationString = "\r\n" + (emitComments ? "//Entry point\r\n" : "") + "void main(void) {\r\n" + this.compilationString;
if (this._constantDeclaration) {
this.compilationString = "\r\n" + (emitComments ? "//Constants\r\n" : "") + this._constantDeclaration + "\r\n" + this.compilationString;
}
var functionCode = "";
for (var functionName in this.functions) {
functionCode += this.functions[functionName] + "\r\n";
}
this.compilationString = "\r\n" + functionCode + "\r\n" + this.compilationString;
if (!isFragmentMode && this._varyingTransfer) {
this.compilationString = this.compilationString + "\r\n" + this._varyingTransfer;
}
if (this._injectAtEnd) {
this.compilationString = this.compilationString + "\r\n" + this._injectAtEnd;
}
this.compilationString = this.compilationString + "\r\n}";
if (this.sharedData.varyingDeclaration) {
this.compilationString = "\r\n" + (emitComments ? "//Varyings\r\n" : "") + this.sharedData.varyingDeclaration + "\r\n" + this.compilationString;
}
if (this._samplerDeclaration) {
this.compilationString = "\r\n" + (emitComments ? "//Samplers\r\n" : "") + this._samplerDeclaration + "\r\n" + this.compilationString;
}
if (this._uniformDeclaration) {
this.compilationString = "\r\n" + (emitComments ? "//Uniforms\r\n" : "") + this._uniformDeclaration + "\r\n" + this.compilationString;
}
if (this._attributeDeclaration && !isFragmentMode) {
this.compilationString = "\r\n" + (emitComments ? "//Attributes\r\n" : "") + this._attributeDeclaration + "\r\n" + this.compilationString;
}
for (var extensionName in this.extensions) {
var extension = this.extensions[extensionName];
this.compilationString = "\r\n" + extension + "\r\n" + this.compilationString;
}
this._builtCompilationString = this.compilationString;
};
Object.defineProperty(NodeMaterialBuildState.prototype, "_repeatableContentAnchor", {
/** @hidden */
get: function () {
return "###___ANCHOR" + this._repeatableContentAnchorIndex++ + "___###";
},
enumerable: false,
configurable: true
});
/** @hidden */
NodeMaterialBuildState.prototype._getFreeVariableName = function (prefix) {
prefix = prefix.replace(/[^a-zA-Z_]+/g, "");
if (this.sharedData.variableNames[prefix] === undefined) {
this.sharedData.variableNames[prefix] = 0;
// Check reserved words
if (prefix === "output" || prefix === "texture") {
return prefix + this.sharedData.variableNames[prefix];
}
return prefix;
}
else {
this.sharedData.variableNames[prefix]++;
}
return prefix + this.sharedData.variableNames[prefix];
};
/** @hidden */
NodeMaterialBuildState.prototype._getFreeDefineName = function (prefix) {
if (this.sharedData.defineNames[prefix] === undefined) {
this.sharedData.defineNames[prefix] = 0;
}
else {
this.sharedData.defineNames[prefix]++;
}
return prefix + this.sharedData.defineNames[prefix];
};
/** @hidden */
NodeMaterialBuildState.prototype._excludeVariableName = function (name) {
this.sharedData.variableNames[name] = 0;
};
/** @hidden */
NodeMaterialBuildState.prototype._emit2DSampler = function (name) {
this._samplerDeclaration += "uniform sampler2D " + name + ";\r\n";
this.samplers.push(name);
};
/** @hidden */
NodeMaterialBuildState.prototype._getGLType = function (type) {
switch (type) {
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Float:
return "float";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Int:
return "int";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector2:
return "vec2";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color3:
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector3:
return "vec3";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Color4:
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Vector4:
return "vec4";
case _Enums_nodeMaterialBlockConnectionPointTypes__WEBPACK_IMPORTED_MODULE_0__["NodeMaterialBlockConnectionPointTypes"].Matrix:
return "mat4";
}
return "";
};
/** @hidden */
NodeMaterialBuildState.prototype._emitExtension = function (name, extension, define) {
if (define === void 0) { define = ""; }
if (this.extensions[name]) {
return;
}
if (define) {
extension = "#if " + define + "\r\n" + extension + "\r\n#endif";
}
this.extensions[name] = extension;
};
/** @hidden */
NodeMaterialBuildState.prototype._emitFunction = function (name, code, comments) {
if (this.functions[name]) {
return;
}
if (this.sharedData.emitComments) {
code = comments + "\r\n" + code;
}
this.functions[name] = code;
};
/** @hidden */
NodeMaterialBuildState.prototype._emitCodeFromInclude = function (includeName, comments, options) {
if (options && options.repeatKey) {
return "#include<" + includeName + ">[0.." + options.repeatKey + "]\r\n";
}
var code = _effect__WEBPACK_IMPORTED_MODULE_2__["Effect"].IncludesShadersStore[includeName] + "\r\n";
if (this.sharedData.emitComments) {
code = comments + "\r\n" + code;
}
if (!options) {
return code;
}
if (options.replaceStrings) {
for (var index = 0; index < options.replaceStrings.length; index++) {
var replaceString = options.replaceStrings[index];
code = code.replace(replaceString.search, replaceString.replace);
}
}
return code;
};
/** @hidden */
NodeMaterialBuildState.prototype._emitFunctionFromInclude = function (includeName, comments, options, storeKey) {
if (storeKey === void 0) { storeKey = ""; }
var key = includeName + storeKey;
if (this.functions[key]) {
return;
}
if (!options || (!options.removeAttributes && !options.removeUniforms && !options.removeVaryings && !options.removeIfDef && !options.replaceStrings)) {
if (options && options.repeatKey) {
this.functions[key] = "#include<" + includeName + ">[0.." + options.repeatKey + "]\r\n";
}
else {
this.functions[key] = "#include<" + includeName + ">\r\n";
}
if (this.sharedData.emitComments) {
this.functions[key] = comments + "\r\n" + this.functions[key];
}
return;
}
this.functions[key] = _effect__WEBPACK_IMPORTED_MODULE_2__["Effect"].IncludesShadersStore[includeName];
if (this.sharedData.emitComments) {
this.functions[key] = comments + "\r\n" + this.functions[key];
}
if (options.removeIfDef) {
this.functions[key] = this.functions[key].replace(/^\s*?#ifdef.+$/gm, "");
this.functions[key] = this.functions[key].replace(/^\s*?#endif.*$/gm, "");
this.functions[key] = this.functions[key].replace(/^\s*?#else.*$/gm, "");
this.functions[key] = this.functions[key].replace(/^\s*?#elif.*$/gm, "");
}
if (options.removeAttributes) {
this.functions[key] = this.functions[key].replace(/^\s*?attribute.+$/gm, "");
}
if (options.removeUniforms) {
this.functions[key] = this.functions[key].replace(/^\s*?uniform.+$/gm, "");
}
if (options.removeVaryings) {
this.functions[key] = this.functions[key].replace(/^\s*?varying.+$/gm, "");
}
if (options.replaceStrings) {
for (var index = 0; index < options.replaceStrings.length; index++) {
var replaceString = options.replaceStrings[index];
this.functions[key] = this.functions[key].replace(replaceString.search, replaceString.replace);
}
}
};
/** @hidden */
NodeMaterialBuildState.prototype._registerTempVariable = function (name) {
if (this.sharedData.temps.indexOf(name) !== -1) {
return false;
}
this.sharedData.temps.push(name);
return true;
};
/** @hidden */
NodeMaterialBuildState.prototype._emitVaryingFromString = function (name, type, define, notDefine) {
if (define === void 0) { define = ""; }
if (notDefine === void 0) { notDefine = false; }
if (this.sharedData.varyings.indexOf(name) !== -1) {
return false;
}
this.sharedData.varyings.push(name);
if (define) {
if (_Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__["StringTools"].StartsWith(define, "defined(")) {
this.sharedData.varyingDeclaration += "#if " + define + "\r\n";
}
else {
this.sharedData.varyingDeclaration += (notDefine ? "#ifndef" : "#ifdef") + " " + define + "\r\n";
}
}
this.sharedData.varyingDeclaration += "varying " + type + " " + name + ";\r\n";
if (define) {
this.sharedData.varyingDeclaration += "#endif\r\n";
}
return true;
};
/** @hidden */
NodeMaterialBuildState.prototype._emitUniformFromString = function (name, type, define, notDefine) {
if (define === void 0) { define = ""; }
if (notDefine === void 0) { notDefine = false; }
if (this.uniforms.indexOf(name) !== -1) {
return;
}
this.uniforms.push(name);
if (define) {
if (_Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__["StringTools"].StartsWith(define, "defined(")) {
this._uniformDeclaration += "#if " + define + "\r\n";
}
else {
this._uniformDeclaration += (notDefine ? "#ifndef" : "#ifdef") + " " + define + "\r\n";
}
}
this._uniformDeclaration += "uniform " + type + " " + name + ";\r\n";
if (define) {
this._uniformDeclaration += "#endif\r\n";
}
};
/** @hidden */
NodeMaterialBuildState.prototype._emitFloat = function (value) {
if (value.toString() === value.toFixed(0)) {
return value + ".0";
}
return value.toString();
};
return NodeMaterialBuildState;
}());
/***/ }),
/***/ "./Materials/Node/nodeMaterialBuildStateSharedData.ts":
/*!************************************************************!*\
!*** ./Materials/Node/nodeMaterialBuildStateSharedData.ts ***!
\************************************************************/
/*! exports provided: NodeMaterialBuildStateSharedData */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialBuildStateSharedData", function() { return NodeMaterialBuildStateSharedData; });
/**
* Class used to store shared data between 2 NodeMaterialBuildState
*/
var NodeMaterialBuildStateSharedData = /** @class */ (function () {
/** Creates a new shared data */
function NodeMaterialBuildStateSharedData() {
/**
* Gets the list of emitted varyings
*/
this.temps = new Array();
/**
* Gets the list of emitted varyings
*/
this.varyings = new Array();
/**
* Gets the varying declaration string
*/
this.varyingDeclaration = "";
/**
* Input blocks
*/
this.inputBlocks = new Array();
/**
* Input blocks
*/
this.textureBlocks = new Array();
/**
* Bindable blocks (Blocks that need to set data to the effect)
*/
this.bindableBlocks = new Array();
/**
* List of blocks that can provide a compilation fallback
*/
this.blocksWithFallbacks = new Array();
/**
* List of blocks that can provide a define update
*/
this.blocksWithDefines = new Array();
/**
* List of blocks that can provide a repeatable content
*/
this.repeatableContentBlocks = new Array();
/**
* List of blocks that can provide a dynamic list of uniforms
*/
this.dynamicUniformBlocks = new Array();
/**
* List of blocks that can block the isReady function for the material
*/
this.blockingBlocks = new Array();
/**
* Gets the list of animated inputs
*/
this.animatedInputs = new Array();
/** List of emitted variables */
this.variableNames = {};
/** List of emitted defines */
this.defineNames = {};
/**
* Gets the compilation hints emitted at compilation time
*/
this.hints = {
needWorldViewMatrix: false,
needWorldViewProjectionMatrix: false,
needAlphaBlending: false,
needAlphaTesting: false
};
/**
* List of compilation checks
*/
this.checks = {
emitVertex: false,
emitFragment: false,
notConnectedNonOptionalInputs: new Array()
};
/**
* Is vertex program allowed to be empty?
*/
this.allowEmptyVertexProgram = false;
// Exclude usual attributes from free variable names
this.variableNames["position"] = 0;
this.variableNames["normal"] = 0;
this.variableNames["tangent"] = 0;
this.variableNames["uv"] = 0;
this.variableNames["uv2"] = 0;
this.variableNames["uv3"] = 0;
this.variableNames["uv4"] = 0;
this.variableNames["uv4"] = 0;
this.variableNames["uv5"] = 0;
this.variableNames["uv6"] = 0;
this.variableNames["color"] = 0;
this.variableNames["matricesIndices"] = 0;
this.variableNames["matricesWeights"] = 0;
this.variableNames["matricesIndicesExtra"] = 0;
this.variableNames["matricesWeightsExtra"] = 0;
this.variableNames["diffuseBase"] = 0;
this.variableNames["specularBase"] = 0;
this.variableNames["worldPos"] = 0;
this.variableNames["shadow"] = 0;
// Exclude known varyings
this.variableNames["vTBN"] = 0;
// Exclude defines
this.defineNames["MAINUV0"] = 0;
this.defineNames["MAINUV1"] = 0;
this.defineNames["MAINUV2"] = 0;
this.defineNames["MAINUV3"] = 0;
this.defineNames["MAINUV4"] = 0;
this.defineNames["MAINUV5"] = 0;
this.defineNames["MAINUV6"] = 0;
this.defineNames["MAINUV7"] = 0;
}
/**
* Emits console errors and exceptions if there is a failing check
*/
NodeMaterialBuildStateSharedData.prototype.emitErrors = function () {
var errorMessage = "";
if (!this.checks.emitVertex && !this.allowEmptyVertexProgram) {
errorMessage += "NodeMaterial does not have a vertex output. You need to at least add a block that generates a glPosition value.\r\n";
}
if (!this.checks.emitFragment) {
errorMessage += "NodeMaterial does not have a fragment output. You need to at least add a block that generates a glFragColor value.\r\n";
}
for (var _i = 0, _a = this.checks.notConnectedNonOptionalInputs; _i < _a.length; _i++) {
var notConnectedInput = _a[_i];
errorMessage += "input " + notConnectedInput.name + " from block " + notConnectedInput.ownerBlock.name + "[" + notConnectedInput.ownerBlock.getClassName() + "] is not connected and is not optional.\r\n";
}
if (errorMessage) {
throw "Build of NodeMaterial failed:\r\n" + errorMessage;
}
};
return NodeMaterialBuildStateSharedData;
}());
/***/ }),
/***/ "./Materials/Node/nodeMaterialConnectionPointCustomObject.ts":
/*!*******************************************************************!*\
!*** ./Materials/Node/nodeMaterialConnectionPointCustomObject.ts ***!
\*******************************************************************/
/*! exports provided: NodeMaterialConnectionPointCustomObject */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeMaterialConnectionPointCustomObject", function() { return NodeMaterialConnectionPointCustomObject; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./nodeMaterialBlockConnectionPoint */ "./Materials/Node/nodeMaterialBlockConnectionPoint.ts");
/**
* Defines a connection point to be used for points with a custom object type
*/
var NodeMaterialConnectionPointCustomObject = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NodeMaterialConnectionPointCustomObject, _super);
/**
* Creates a new connection point
* @param name defines the connection point name
* @param ownerBlock defines the block hosting this connection point
* @param direction defines the direction of the connection point
*/
function NodeMaterialConnectionPointCustomObject(name, ownerBlock, direction, _blockType, _blockName, _nameForCheking) {
var _this = _super.call(this, name, ownerBlock, direction) || this;
_this._blockType = _blockType;
_this._blockName = _blockName;
_this._nameForCheking = _nameForCheking;
if (!_this._nameForCheking) {
_this._nameForCheking = name;
}
_this.needDualDirectionValidation = true;
return _this;
}
/**
* Gets a number indicating if the current point can be connected to another point
* @param connectionPoint defines the other connection point
* @returns a number defining the compatibility state
*/
NodeMaterialConnectionPointCustomObject.prototype.checkCompatibilityState = function (connectionPoint) {
return connectionPoint instanceof NodeMaterialConnectionPointCustomObject && connectionPoint.name === this._nameForCheking ?
_nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPointCompatibilityStates"].Compatible : _nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPointCompatibilityStates"].TypeIncompatible;
};
/**
* Creates a block suitable to be used as an input for this input point.
* If null is returned, a block based on the point type will be created.
* @returns The returned string parameter is the name of the output point of NodeMaterialBlock (first parameter of the returned array) that can be connected to the input
*/
NodeMaterialConnectionPointCustomObject.prototype.createCustomInputBlock = function () {
return [new this._blockType(this._blockName), this.name];
};
return NodeMaterialConnectionPointCustomObject;
}(_nodeMaterialBlockConnectionPoint__WEBPACK_IMPORTED_MODULE_1__["NodeMaterialConnectionPoint"]));
/***/ }),
/***/ "./Materials/Node/nodeMaterialDecorator.ts":
/*!*************************************************!*\
!*** ./Materials/Node/nodeMaterialDecorator.ts ***!
\*************************************************/
/*! exports provided: PropertyTypeForEdition, editableInPropertyPage */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyTypeForEdition", function() { return PropertyTypeForEdition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "editableInPropertyPage", function() { return editableInPropertyPage; });
/**
* Enum defining the type of properties that can be edited in the property pages in the NME
*/
var PropertyTypeForEdition;
(function (PropertyTypeForEdition) {
/** property is a boolean */
PropertyTypeForEdition[PropertyTypeForEdition["Boolean"] = 0] = "Boolean";
/** property is a float */
PropertyTypeForEdition[PropertyTypeForEdition["Float"] = 1] = "Float";
/** property is a Vector2 */
PropertyTypeForEdition[PropertyTypeForEdition["Vector2"] = 2] = "Vector2";
/** property is a list of values */
PropertyTypeForEdition[PropertyTypeForEdition["List"] = 3] = "List";
})(PropertyTypeForEdition || (PropertyTypeForEdition = {}));
/**
* Decorator that flags a property in a node material block as being editable
*/
function editableInPropertyPage(displayName, propertyType, groupName, options) {
if (propertyType === void 0) { propertyType = PropertyTypeForEdition.Boolean; }
if (groupName === void 0) { groupName = "PROPERTIES"; }
return function (target, propertyKey) {
var propStore = target._propStore;
if (!propStore) {
propStore = [];
target._propStore = propStore;
}
propStore.push({
"propertyName": propertyKey,
"displayName": displayName,
"type": propertyType,
"groupName": groupName,
"options": options !== null && options !== void 0 ? options : {}
});
};
}
/***/ }),
/***/ "./Materials/PBR/index.ts":
/*!********************************!*\
!*** ./Materials/PBR/index.ts ***!
\********************************/
/*! exports provided: PBRMaterialDefines, PBRBaseMaterial, PBRBaseSimpleMaterial, PBRMaterial, PBRMetallicRoughnessMaterial, PBRSpecularGlossinessMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRMaterialDefines"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_0__["PBRBaseMaterial"]; });
/* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_1__["PBRBaseSimpleMaterial"]; });
/* harmony import */ var _pbrMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrMaterial */ "./Materials/PBR/pbrMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return _pbrMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRMaterial"]; });
/* harmony import */ var _pbrMetallicRoughnessMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pbrMetallicRoughnessMaterial */ "./Materials/PBR/pbrMetallicRoughnessMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return _pbrMetallicRoughnessMaterial__WEBPACK_IMPORTED_MODULE_3__["PBRMetallicRoughnessMaterial"]; });
/* harmony import */ var _pbrSpecularGlossinessMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pbrSpecularGlossinessMaterial */ "./Materials/PBR/pbrSpecularGlossinessMaterial.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return _pbrSpecularGlossinessMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRSpecularGlossinessMaterial"]; });
/***/ }),
/***/ "./Materials/PBR/pbrAnisotropicConfiguration.ts":
/*!******************************************************!*\
!*** ./Materials/PBR/pbrAnisotropicConfiguration.ts ***!
\******************************************************/
/*! exports provided: PBRAnisotropicConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRAnisotropicConfiguration", function() { return PBRAnisotropicConfiguration; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/**
* Define the code related to the anisotropic parameters of the pbr material.
*/
var PBRAnisotropicConfiguration = /** @class */ (function () {
/**
* Instantiate a new istance of anisotropy configuration.
* @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty
*/
function PBRAnisotropicConfiguration(markAllSubMeshesAsTexturesDirty) {
this._isEnabled = false;
/**
* Defines if the anisotropy is enabled in the material.
*/
this.isEnabled = false;
/**
* Defines the anisotropy strength (between 0 and 1) it defaults to 1.
*/
this.intensity = 1;
/**
* Defines if the effect is along the tangents, bitangents or in between.
* By default, the effect is "strectching" the highlights along the tangents.
*/
this.direction = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_3__["Vector2"](1, 0);
this._texture = null;
/**
* Stores the anisotropy values in a texture.
* rg is direction (like normal from -1 to 1)
* b is a intensity
*/
this.texture = null;
this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty;
}
/** @hidden */
PBRAnisotropicConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () {
this._internalMarkAllSubMeshesAsTexturesDirty();
};
/**
* Specifies that the submesh is ready to be used.
* @param defines the list of "defines" to update.
* @param scene defines the scene the material belongs to.
* @returns - boolean indicating that the submesh is ready or not.
*/
PBRAnisotropicConfiguration.prototype.isReadyForSubMesh = function (defines, scene) {
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) {
if (!this._texture.isReadyOrNotBlocking()) {
return false;
}
}
}
}
return true;
};
/**
* Checks to see if a texture is used in the material.
* @param defines the list of "defines" to update.
* @param mesh the mesh we are preparing the defines for.
* @param scene defines the scene the material belongs to.
*/
PBRAnisotropicConfiguration.prototype.prepareDefines = function (defines, mesh, scene) {
if (this._isEnabled) {
defines.ANISOTROPIC = this._isEnabled;
if (this._isEnabled && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_2__["VertexBuffer"].TangentKind)) {
defines._needUVs = true;
defines.MAINUV1 = true;
}
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "ANISOTROPIC_TEXTURE");
}
else {
defines.ANISOTROPIC_TEXTURE = false;
}
}
}
}
else {
defines.ANISOTROPIC = false;
defines.ANISOTROPIC_TEXTURE = false;
}
};
/**
* Binds the material data.
* @param uniformBuffer defines the Uniform buffer to fill in.
* @param scene defines the scene the material belongs to.
* @param isFrozen defines wether the material is frozen or not.
*/
PBRAnisotropicConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, isFrozen) {
if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) {
uniformBuffer.updateFloat2("vAnisotropyInfos", this._texture.coordinatesIndex, this._texture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_5__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "anisotropy");
}
// Anisotropy
uniformBuffer.updateFloat3("vAnisotropy", this.direction.x, this.direction.y, this.intensity);
}
// Textures
if (scene.texturesEnabled) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_4__["MaterialFlags"].AnisotropicTextureEnabled) {
uniformBuffer.setTexture("anisotropySampler", this._texture);
}
}
};
/**
* Checks to see if a texture is used in the material.
* @param texture - Base texture to use.
* @returns - Boolean specifying if a texture is used in the material.
*/
PBRAnisotropicConfiguration.prototype.hasTexture = function (texture) {
if (this._texture === texture) {
return true;
}
return false;
};
/**
* Returns an array of the actively used textures.
* @param activeTextures Array of BaseTextures
*/
PBRAnisotropicConfiguration.prototype.getActiveTextures = function (activeTextures) {
if (this._texture) {
activeTextures.push(this._texture);
}
};
/**
* Returns the animatable textures.
* @param animatables Array of animatable textures.
*/
PBRAnisotropicConfiguration.prototype.getAnimatables = function (animatables) {
if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
animatables.push(this._texture);
}
};
/**
* Disposes the resources of the material.
* @param forceDisposeTextures - Forces the disposal of all textures.
*/
PBRAnisotropicConfiguration.prototype.dispose = function (forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._texture) {
this._texture.dispose();
}
}
};
/**
* Get the current class name of the texture useful for serialization or dynamic coding.
* @returns "PBRAnisotropicConfiguration"
*/
PBRAnisotropicConfiguration.prototype.getClassName = function () {
return "PBRAnisotropicConfiguration";
};
/**
* Add fallbacks to the effect fallbacks list.
* @param defines defines the Base texture to use.
* @param fallbacks defines the current fallback list.
* @param currentRank defines the current fallback rank.
* @returns the new fallback rank.
*/
PBRAnisotropicConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) {
if (defines.ANISOTROPIC) {
fallbacks.addFallback(currentRank++, "ANISOTROPIC");
}
return currentRank;
};
/**
* Add the required uniforms to the current list.
* @param uniforms defines the current uniform list.
*/
PBRAnisotropicConfiguration.AddUniforms = function (uniforms) {
uniforms.push("vAnisotropy", "vAnisotropyInfos", "anisotropyMatrix");
};
/**
* Add the required uniforms to the current buffer.
* @param uniformBuffer defines the current uniform buffer.
*/
PBRAnisotropicConfiguration.PrepareUniformBuffer = function (uniformBuffer) {
uniformBuffer.addUniform("vAnisotropy", 3);
uniformBuffer.addUniform("vAnisotropyInfos", 2);
uniformBuffer.addUniform("anisotropyMatrix", 16);
};
/**
* Add the required samplers to the current list.
* @param samplers defines the current sampler list.
*/
PBRAnisotropicConfiguration.AddSamplers = function (samplers) {
samplers.push("anisotropySampler");
};
/**
* Makes a duplicate of the current configuration into another one.
* @param anisotropicConfiguration define the config where to copy the info
*/
PBRAnisotropicConfiguration.prototype.copyTo = function (anisotropicConfiguration) {
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return anisotropicConfiguration; }, this);
};
/**
* Serializes this anisotropy configuration.
* @returns - An object with the serialized config.
*/
PBRAnisotropicConfiguration.prototype.serialize = function () {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
};
/**
* Parses a anisotropy Configuration from a serialized object.
* @param source - Serialized object.
* @param scene Defines the scene we are parsing for
* @param rootUrl Defines the rootUrl to load from
*/
PBRAnisotropicConfiguration.prototype.parse = function (source, scene, rootUrl) {
var _this = this;
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, scene, rootUrl);
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRAnisotropicConfiguration.prototype, "isEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRAnisotropicConfiguration.prototype, "intensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsVector2"])()
], PBRAnisotropicConfiguration.prototype, "direction", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRAnisotropicConfiguration.prototype, "texture", void 0);
return PBRAnisotropicConfiguration;
}());
/***/ }),
/***/ "./Materials/PBR/pbrBRDFConfiguration.ts":
/*!***********************************************!*\
!*** ./Materials/PBR/pbrBRDFConfiguration.ts ***!
\***********************************************/
/*! exports provided: PBRBRDFConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBRDFConfiguration", function() { return PBRBRDFConfiguration; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/**
* Define the code related to the BRDF parameters of the pbr material.
*/
var PBRBRDFConfiguration = /** @class */ (function () {
/**
* Instantiate a new istance of clear coat configuration.
* @param markAllSubMeshesAsMiscDirty Callback to flag the material to dirty
*/
function PBRBRDFConfiguration(markAllSubMeshesAsMiscDirty) {
this._useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;
/**
* Defines if the material uses energy conservation.
*/
this.useEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION;
this._useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;
/**
* LEGACY Mode set to false
* Defines if the material uses height smith correlated visibility term.
* If you intent to not use our default BRDF, you need to load a separate BRDF Texture for the PBR
* You can either load https://assets.babylonjs.com/environments/uncorrelatedBRDF.png
* or https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds to have more precision
* Not relying on height correlated will also disable energy conservation.
*/
this.useSmithVisibilityHeightCorrelated = PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED;
this._useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;
/**
* LEGACY Mode set to false
* Defines if the material uses spherical harmonics vs spherical polynomials for the
* diffuse part of the IBL.
* The harmonics despite a tiny bigger cost has been proven to provide closer results
* to the ground truth.
*/
this.useSphericalHarmonics = PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS;
this._useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;
/**
* Defines if the material uses energy conservation, when the specular workflow is active.
* If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).
* If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.
* In the deactivated case, the material author has to ensure energy conservation, for a physically plausible rendering.
*/
this.useSpecularGlossinessInputEnergyConservation = PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION;
this._internalMarkAllSubMeshesAsMiscDirty = markAllSubMeshesAsMiscDirty;
}
/** @hidden */
PBRBRDFConfiguration.prototype._markAllSubMeshesAsMiscDirty = function () {
this._internalMarkAllSubMeshesAsMiscDirty();
};
/**
* Checks to see if a texture is used in the material.
* @param defines the list of "defines" to update.
*/
PBRBRDFConfiguration.prototype.prepareDefines = function (defines) {
defines.BRDF_V_HEIGHT_CORRELATED = this._useSmithVisibilityHeightCorrelated;
defines.MS_BRDF_ENERGY_CONSERVATION = this._useEnergyConservation && this._useSmithVisibilityHeightCorrelated;
defines.SPHERICAL_HARMONICS = this._useSphericalHarmonics;
defines.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = this._useSpecularGlossinessInputEnergyConservation;
};
/**
* Get the current class name of the texture useful for serialization or dynamic coding.
* @returns "PBRClearCoatConfiguration"
*/
PBRBRDFConfiguration.prototype.getClassName = function () {
return "PBRBRDFConfiguration";
};
/**
* Makes a duplicate of the current configuration into another one.
* @param brdfConfiguration define the config where to copy the info
*/
PBRBRDFConfiguration.prototype.copyTo = function (brdfConfiguration) {
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return brdfConfiguration; }, this);
};
/**
* Serializes this BRDF configuration.
* @returns - An object with the serialized config.
*/
PBRBRDFConfiguration.prototype.serialize = function () {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
};
/**
* Parses a anisotropy Configuration from a serialized object.
* @param source - Serialized object.
* @param scene Defines the scene we are parsing for
* @param rootUrl Defines the rootUrl to load from
*/
PBRBRDFConfiguration.prototype.parse = function (source, scene, rootUrl) {
var _this = this;
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, scene, rootUrl);
};
/**
* Default value used for the energy conservation.
* This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.
*/
PBRBRDFConfiguration.DEFAULT_USE_ENERGY_CONSERVATION = true;
/**
* Default value used for the Smith Visibility Height Correlated mode.
* This should only be changed to adapt to the type of texture in scene.environmentBRDFTexture.
*/
PBRBRDFConfiguration.DEFAULT_USE_SMITH_VISIBILITY_HEIGHT_CORRELATED = true;
/**
* Default value used for the IBL diffuse part.
* This can help switching back to the polynomials mode globally which is a tiny bit
* less GPU intensive at the drawback of a lower quality.
*/
PBRBRDFConfiguration.DEFAULT_USE_SPHERICAL_HARMONICS = true;
/**
* Default value used for activating energy conservation for the specular workflow.
* If activated, the albedo color is multiplied with (1. - maxChannel(specular color)).
* If deactivated, a material is only physically plausible, when (albedo color + specular color) < 1.
*/
PBRBRDFConfiguration.DEFAULT_USE_SPECULAR_GLOSSINESS_INPUT_ENERGY_CONSERVATION = true;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useEnergyConservation", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useSmithVisibilityHeightCorrelated", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useSphericalHarmonics", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty")
], PBRBRDFConfiguration.prototype, "useSpecularGlossinessInputEnergyConservation", void 0);
return PBRBRDFConfiguration;
}());
/***/ }),
/***/ "./Materials/PBR/pbrBaseMaterial.ts":
/*!******************************************!*\
!*** ./Materials/PBR/pbrBaseMaterial.ts ***!
\******************************************/
/*! exports provided: PBRMaterialDefines, PBRBaseMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMaterialDefines", function() { return PBRMaterialDefines; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBaseMaterial", function() { return PBRBaseMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_smartArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/smartArray */ "./Misc/smartArray.ts");
/* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts");
/* harmony import */ var _scene__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../scene */ "./scene.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ./pbrClearCoatConfiguration */ "./Materials/PBR/pbrClearCoatConfiguration.ts");
/* harmony import */ var _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! ./pbrAnisotropicConfiguration */ "./Materials/PBR/pbrAnisotropicConfiguration.ts");
/* harmony import */ var _pbrBRDFConfiguration__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! ./pbrBRDFConfiguration */ "./Materials/PBR/pbrBRDFConfiguration.ts");
/* harmony import */ var _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! ./pbrSheenConfiguration */ "./Materials/PBR/pbrSheenConfiguration.ts");
/* harmony import */ var _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! ./pbrSubSurfaceConfiguration */ "./Materials/PBR/pbrSubSurfaceConfiguration.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! ../../Maths/math.scalar */ "./Maths/math.scalar.ts");
/* harmony import */ var _Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! ../../Materials/imageProcessingConfiguration */ "./Materials/imageProcessingConfiguration.ts");
/* harmony import */ var _Materials_material__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! ../../Materials/material */ "./Materials/material.ts");
/* harmony import */ var _Materials_materialDefines__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ../../Materials/materialDefines */ "./Materials/materialDefines.ts");
/* harmony import */ var _Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! ../../Materials/pushMaterial */ "./Materials/pushMaterial.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(/*! ../../Materials/Textures/texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Materials_Textures_baseTexture_polynomial__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(/*! ../../Materials/Textures/baseTexture.polynomial */ "./Materials/Textures/baseTexture.polynomial.ts");
/* harmony import */ var _Shaders_pbr_fragment__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(/*! ../../Shaders/pbr.fragment */ "./Shaders/pbr.fragment.ts");
/* harmony import */ var _Shaders_pbr_vertex__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(/*! ../../Shaders/pbr.vertex */ "./Shaders/pbr.vertex.ts");
/* harmony import */ var _effectFallbacks__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(/*! ../effectFallbacks */ "./Materials/effectFallbacks.ts");
/* harmony import */ var _material_detailMapConfiguration__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(/*! ../material.detailMapConfiguration */ "./Materials/material.detailMapConfiguration.ts");
var onCreatedEffectParameters = { effect: null, subMesh: null };
/**
* Manages the defines for the PBR Material.
* @hidden
*/
var PBRMaterialDefines = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRMaterialDefines, _super);
/**
* Initializes the PBR Material defines.
*/
function PBRMaterialDefines() {
var _this = _super.call(this) || this;
_this.PBR = true;
_this.NUM_SAMPLES = "0";
_this.REALTIME_FILTERING = false;
_this.MAINUV1 = false;
_this.MAINUV2 = false;
_this.UV1 = false;
_this.UV2 = false;
_this.ALBEDO = false;
_this.GAMMAALBEDO = false;
_this.ALBEDODIRECTUV = 0;
_this.VERTEXCOLOR = false;
_this.DETAIL = false;
_this.DETAILDIRECTUV = 0;
_this.DETAIL_NORMALBLENDMETHOD = 0;
_this.AMBIENT = false;
_this.AMBIENTDIRECTUV = 0;
_this.AMBIENTINGRAYSCALE = false;
_this.OPACITY = false;
_this.VERTEXALPHA = false;
_this.OPACITYDIRECTUV = 0;
_this.OPACITYRGB = false;
_this.ALPHATEST = false;
_this.DEPTHPREPASS = false;
_this.ALPHABLEND = false;
_this.ALPHAFROMALBEDO = false;
_this.ALPHATESTVALUE = "0.5";
_this.SPECULAROVERALPHA = false;
_this.RADIANCEOVERALPHA = false;
_this.ALPHAFRESNEL = false;
_this.LINEARALPHAFRESNEL = false;
_this.PREMULTIPLYALPHA = false;
_this.EMISSIVE = false;
_this.EMISSIVEDIRECTUV = 0;
_this.REFLECTIVITY = false;
_this.REFLECTIVITYDIRECTUV = 0;
_this.SPECULARTERM = false;
_this.MICROSURFACEFROMREFLECTIVITYMAP = false;
_this.MICROSURFACEAUTOMATIC = false;
_this.LODBASEDMICROSFURACE = false;
_this.MICROSURFACEMAP = false;
_this.MICROSURFACEMAPDIRECTUV = 0;
_this.METALLICWORKFLOW = false;
_this.ROUGHNESSSTOREINMETALMAPALPHA = false;
_this.ROUGHNESSSTOREINMETALMAPGREEN = false;
_this.METALLNESSSTOREINMETALMAPBLUE = false;
_this.AOSTOREINMETALMAPRED = false;
_this.METALLIC_REFLECTANCE = false;
_this.METALLIC_REFLECTANCEDIRECTUV = 0;
_this.ENVIRONMENTBRDF = false;
_this.ENVIRONMENTBRDF_RGBD = false;
_this.NORMAL = false;
_this.TANGENT = false;
_this.BUMP = false;
_this.BUMPDIRECTUV = 0;
_this.OBJECTSPACE_NORMALMAP = false;
_this.PARALLAX = false;
_this.PARALLAXOCCLUSION = false;
_this.NORMALXYSCALE = true;
_this.LIGHTMAP = false;
_this.LIGHTMAPDIRECTUV = 0;
_this.USELIGHTMAPASSHADOWMAP = false;
_this.GAMMALIGHTMAP = false;
_this.RGBDLIGHTMAP = false;
_this.REFLECTION = false;
_this.REFLECTIONMAP_3D = false;
_this.REFLECTIONMAP_SPHERICAL = false;
_this.REFLECTIONMAP_PLANAR = false;
_this.REFLECTIONMAP_CUBIC = false;
_this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
_this.REFLECTIONMAP_PROJECTION = false;
_this.REFLECTIONMAP_SKYBOX = false;
_this.REFLECTIONMAP_EXPLICIT = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR = false;
_this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
_this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
_this.INVERTCUBICMAP = false;
_this.USESPHERICALFROMREFLECTIONMAP = false;
_this.USEIRRADIANCEMAP = false;
_this.SPHERICAL_HARMONICS = false;
_this.USESPHERICALINVERTEX = false;
_this.REFLECTIONMAP_OPPOSITEZ = false;
_this.LODINREFLECTIONALPHA = false;
_this.GAMMAREFLECTION = false;
_this.RGBDREFLECTION = false;
_this.LINEARSPECULARREFLECTION = false;
_this.RADIANCEOCCLUSION = false;
_this.HORIZONOCCLUSION = false;
_this.INSTANCES = false;
_this.THIN_INSTANCES = false;
_this.PREPASS = false;
_this.SCENE_MRT_COUNT = 0;
_this.NUM_BONE_INFLUENCERS = 0;
_this.BonesPerMesh = 0;
_this.BONETEXTURE = false;
_this.NONUNIFORMSCALING = false;
_this.MORPHTARGETS = false;
_this.MORPHTARGETS_NORMAL = false;
_this.MORPHTARGETS_TANGENT = false;
_this.MORPHTARGETS_UV = false;
_this.NUM_MORPH_INFLUENCERS = 0;
_this.IMAGEPROCESSING = false;
_this.VIGNETTE = false;
_this.VIGNETTEBLENDMODEMULTIPLY = false;
_this.VIGNETTEBLENDMODEOPAQUE = false;
_this.TONEMAPPING = false;
_this.TONEMAPPING_ACES = false;
_this.CONTRAST = false;
_this.COLORCURVES = false;
_this.COLORGRADING = false;
_this.COLORGRADING3D = false;
_this.SAMPLER3DGREENDEPTH = false;
_this.SAMPLER3DBGRMAP = false;
_this.IMAGEPROCESSINGPOSTPROCESS = false;
_this.EXPOSURE = false;
_this.MULTIVIEW = false;
_this.USEPHYSICALLIGHTFALLOFF = false;
_this.USEGLTFLIGHTFALLOFF = false;
_this.TWOSIDEDLIGHTING = false;
_this.SHADOWFLOAT = false;
_this.CLIPPLANE = false;
_this.CLIPPLANE2 = false;
_this.CLIPPLANE3 = false;
_this.CLIPPLANE4 = false;
_this.CLIPPLANE5 = false;
_this.CLIPPLANE6 = false;
_this.POINTSIZE = false;
_this.FOG = false;
_this.LOGARITHMICDEPTH = false;
_this.FORCENORMALFORWARD = false;
_this.SPECULARAA = false;
_this.CLEARCOAT = false;
_this.CLEARCOAT_DEFAULTIOR = false;
_this.CLEARCOAT_TEXTURE = false;
_this.CLEARCOAT_TEXTUREDIRECTUV = 0;
_this.CLEARCOAT_BUMP = false;
_this.CLEARCOAT_BUMPDIRECTUV = 0;
_this.CLEARCOAT_TINT = false;
_this.CLEARCOAT_TINT_TEXTURE = false;
_this.CLEARCOAT_TINT_TEXTUREDIRECTUV = 0;
_this.ANISOTROPIC = false;
_this.ANISOTROPIC_TEXTURE = false;
_this.ANISOTROPIC_TEXTUREDIRECTUV = 0;
_this.BRDF_V_HEIGHT_CORRELATED = false;
_this.MS_BRDF_ENERGY_CONSERVATION = false;
_this.SPECULAR_GLOSSINESS_ENERGY_CONSERVATION = false;
_this.SHEEN = false;
_this.SHEEN_TEXTURE = false;
_this.SHEEN_TEXTUREDIRECTUV = 0;
_this.SHEEN_LINKWITHALBEDO = false;
_this.SHEEN_ROUGHNESS = false;
_this.SHEEN_ALBEDOSCALING = false;
_this.SUBSURFACE = false;
_this.SS_REFRACTION = false;
_this.SS_TRANSLUCENCY = false;
_this.SS_SCATTERING = false;
_this.SS_THICKNESSANDMASK_TEXTURE = false;
_this.SS_THICKNESSANDMASK_TEXTUREDIRECTUV = 0;
_this.SS_REFRACTIONMAP_3D = false;
_this.SS_REFRACTIONMAP_OPPOSITEZ = false;
_this.SS_LODINREFRACTIONALPHA = false;
_this.SS_GAMMAREFRACTION = false;
_this.SS_RGBDREFRACTION = false;
_this.SS_LINEARSPECULARREFRACTION = false;
_this.SS_LINKREFRACTIONTOTRANSPARENCY = false;
_this.SS_ALBEDOFORREFRACTIONTINT = false;
_this.SS_MASK_FROM_THICKNESS_TEXTURE = false;
_this.UNLIT = false;
_this.DEBUGMODE = 0;
_this.rebuild();
return _this;
}
/**
* Resets the PBR Material defines.
*/
PBRMaterialDefines.prototype.reset = function () {
_super.prototype.reset.call(this);
this.ALPHATESTVALUE = "0.5";
this.PBR = true;
};
return PBRMaterialDefines;
}(_Materials_materialDefines__WEBPACK_IMPORTED_MODULE_17__["MaterialDefines"]));
/**
* The Physically based material base class of BJS.
*
* This offers the main features of a standard PBR material.
* For more information, please refer to the documentation :
* https://doc.babylonjs.com/how_to/physically_based_rendering
*/
var PBRBaseMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRBaseMaterial, _super);
/**
* Instantiates a new PBRMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRBaseMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Intensity of the direct lights e.g. the four lights available in your scene.
* This impacts both the direct diffuse and specular highlights.
*/
_this._directIntensity = 1.0;
/**
* Intensity of the emissive part of the material.
* This helps controlling the emissive effect without modifying the emissive color.
*/
_this._emissiveIntensity = 1.0;
/**
* Intensity of the environment e.g. how much the environment will light the object
* either through harmonics for rough material or through the refelction for shiny ones.
*/
_this._environmentIntensity = 1.0;
/**
* This is a special control allowing the reduction of the specular highlights coming from the
* four lights of the scene. Those highlights may not be needed in full environment lighting.
*/
_this._specularIntensity = 1.0;
/**
* This stores the direct, emissive, environment, and specular light intensities into a Vector4.
*/
_this._lightingInfos = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_6__["Vector4"](_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
/**
* Debug Control allowing disabling the bump map on this material.
*/
_this._disableBumpMap = false;
/**
* AKA Diffuse Texture in standard nomenclature.
*/
_this._albedoTexture = null;
/**
* AKA Occlusion Texture in other nomenclature.
*/
_this._ambientTexture = null;
/**
* AKA Occlusion Texture Intensity in other nomenclature.
*/
_this._ambientTextureStrength = 1.0;
/**
* Defines how much the AO map is occluding the analytical lights (point spot...).
* 1 means it completely occludes it
* 0 mean it has no impact
*/
_this._ambientTextureImpactOnAnalyticalLights = PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
/**
* Stores the alpha values in a texture.
*/
_this._opacityTexture = null;
/**
* Stores the reflection values in a texture.
*/
_this._reflectionTexture = null;
/**
* Stores the emissive values in a texture.
*/
_this._emissiveTexture = null;
/**
* AKA Specular texture in other nomenclature.
*/
_this._reflectivityTexture = null;
/**
* Used to switch from specular/glossiness to metallic/roughness workflow.
*/
_this._metallicTexture = null;
/**
* Specifies the metallic scalar of the metallic/roughness workflow.
* Can also be used to scale the metalness values of the metallic texture.
*/
_this._metallic = null;
/**
* Specifies the roughness scalar of the metallic/roughness workflow.
* Can also be used to scale the roughness values of the metallic texture.
*/
_this._roughness = null;
/**
* In metallic workflow, specifies an F0 factor to help configuring the material F0.
* By default the indexOfrefraction is used to compute F0;
*
* This is used as a factor against the default reflectance at normal incidence to tweak it.
*
* F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;
* F90 = metallicReflectanceColor;
*/
_this._metallicF0Factor = 1;
/**
* In metallic workflow, specifies an F90 color to help configuring the material F90.
* By default the F90 is always 1;
*
* Please note that this factor is also used as a factor against the default reflectance at normal incidence.
*
* F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor
* F90 = metallicReflectanceColor;
*/
_this._metallicReflectanceColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"].White();
/**
* Defines to store metallicReflectanceColor in RGB and metallicF0Factor in A
* This is multiply against the scalar values defined in the material.
*/
_this._metallicReflectanceTexture = null;
/**
* Used to enable roughness/glossiness fetch from a separate channel depending on the current mode.
* Gray Scale represents roughness in metallic mode and glossiness in specular mode.
*/
_this._microSurfaceTexture = null;
/**
* Stores surface normal data used to displace a mesh in a texture.
*/
_this._bumpTexture = null;
/**
* Stores the pre-calculated light information of a mesh in a texture.
*/
_this._lightmapTexture = null;
/**
* The color of a material in ambient lighting.
*/
_this._ambientColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"](0, 0, 0);
/**
* AKA Diffuse Color in other nomenclature.
*/
_this._albedoColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"](1, 1, 1);
/**
* AKA Specular Color in other nomenclature.
*/
_this._reflectivityColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"](1, 1, 1);
/**
* The color applied when light is reflected from a material.
*/
_this._reflectionColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"](1, 1, 1);
/**
* The color applied when light is emitted from a material.
*/
_this._emissiveColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"](0, 0, 0);
/**
* AKA Glossiness in other nomenclature.
*/
_this._microSurface = 0.9;
/**
* Specifies that the material will use the light map as a show map.
*/
_this._useLightmapAsShadowmap = false;
/**
* This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
* makes the reflect vector face the model (under horizon).
*/
_this._useHorizonOcclusion = true;
/**
* This parameters will enable/disable radiance occlusion by preventing the radiance to lit
* too much the area relying on ambient texture to define their ambient occlusion.
*/
_this._useRadianceOcclusion = true;
/**
* Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
*/
_this._useAlphaFromAlbedoTexture = false;
/**
* Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
*/
_this._useSpecularOverAlpha = true;
/**
* Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
*/
_this._useMicroSurfaceFromReflectivityMapAlpha = false;
/**
* Specifies if the metallic texture contains the roughness information in its alpha channel.
*/
_this._useRoughnessFromMetallicTextureAlpha = true;
/**
* Specifies if the metallic texture contains the roughness information in its green channel.
*/
_this._useRoughnessFromMetallicTextureGreen = false;
/**
* Specifies if the metallic texture contains the metallness information in its blue channel.
*/
_this._useMetallnessFromMetallicTextureBlue = false;
/**
* Specifies if the metallic texture contains the ambient occlusion information in its red channel.
*/
_this._useAmbientOcclusionFromMetallicTextureRed = false;
/**
* Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
*/
_this._useAmbientInGrayScale = false;
/**
* In case the reflectivity map does not contain the microsurface information in its alpha channel,
* The material will try to infer what glossiness each pixel should be.
*/
_this._useAutoMicroSurfaceFromReflectivityMap = false;
/**
* Defines the falloff type used in this material.
* It by default is Physical.
*/
_this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
/**
* Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
*/
_this._useRadianceOverAlpha = true;
/**
* Allows using an object space normal map (instead of tangent space).
*/
_this._useObjectSpaceNormalMap = false;
/**
* Allows using the bump map in parallax mode.
*/
_this._useParallax = false;
/**
* Allows using the bump map in parallax occlusion mode.
*/
_this._useParallaxOcclusion = false;
/**
* Controls the scale bias of the parallax mode.
*/
_this._parallaxScaleBias = 0.05;
/**
* If sets to true, disables all the lights affecting the material.
*/
_this._disableLighting = false;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this._maxSimultaneousLights = 4;
/**
* If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
*/
_this._invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
*/
_this._invertNormalMapY = false;
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
_this._twoSidedLighting = false;
/**
* Defines the alpha limits in alpha test mode.
*/
_this._alphaCutOff = 0.4;
/**
* Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
*/
_this._forceAlphaTest = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
*/
_this._useAlphaFresnel = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
*/
_this._useLinearAlphaFresnel = false;
/**
* Specifies the environment BRDF texture used to comput the scale and offset roughness values
* from cos thetav and roughness:
* http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
*/
_this._environmentBRDFTexture = null;
/**
* Force the shader to compute irradiance in the fragment shader in order to take bump in account.
*/
_this._forceIrradianceInFragment = false;
_this._realTimeFiltering = false;
_this._realTimeFilteringQuality = _Engines_constants__WEBPACK_IMPORTED_MODULE_22__["Constants"].TEXTURE_FILTERING_QUALITY_LOW;
/**
* Force normal to face away from face.
*/
_this._forceNormalForward = false;
/**
* Enables specular anti aliasing in the PBR shader.
* It will both interacts on the Geometry for analytical and IBL lighting.
* It also prefilter the roughness map based on the bump values.
*/
_this._enableSpecularAntiAliasing = false;
/**
* Keep track of the image processing observer to allow dispose and replace.
*/
_this._imageProcessingObserver = null;
/**
* Stores the available render targets.
*/
_this._renderTargets = new _Misc_smartArray__WEBPACK_IMPORTED_MODULE_3__["SmartArray"](16);
/**
* Sets the global ambient color for the material used in lighting calculations.
*/
_this._globalAmbientColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"](0, 0, 0);
/**
* Enables the use of logarithmic depth buffers, which is good for wide depth buffers.
*/
_this._useLogarithmicDepth = false;
/**
* If set to true, no lighting calculations will be applied.
*/
_this._unlit = false;
_this._debugMode = 0;
/**
* @hidden
* This is reserved for the inspector.
* Defines the material debug mode.
* It helps seeing only some components of the material while troubleshooting.
*/
_this.debugMode = 0;
/**
* @hidden
* This is reserved for the inspector.
* Specify from where on screen the debug mode should start.
* The value goes from -1 (full screen) to 1 (not visible)
* It helps with side by side comparison against the final render
* This defaults to -1
*/
_this.debugLimit = -1;
/**
* @hidden
* This is reserved for the inspector.
* As the default viewing range might not be enough (if the ambient is really small for instance)
* You can use the factor to better multiply the final value.
*/
_this.debugFactor = 1;
/**
* Defines the clear coat layer parameters for the material.
*/
_this.clearCoat = new _pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this));
/**
* Defines the anisotropic parameters for the material.
*/
_this.anisotropy = new _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this));
/**
* Defines the BRDF parameters for the material.
*/
_this.brdf = new _pbrBRDFConfiguration__WEBPACK_IMPORTED_MODULE_10__["PBRBRDFConfiguration"](_this._markAllSubMeshesAsMiscDirty.bind(_this));
/**
* Defines the Sheen parameters for the material.
*/
_this.sheen = new _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this));
/**
* Defines the detail map parameters for the material.
*/
_this.detailMap = new _material_detailMapConfiguration__WEBPACK_IMPORTED_MODULE_27__["DetailMapConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this));
_this._rebuildInParallel = false;
// Setup the default processing configuration to the scene.
_this._attachImageProcessingConfiguration(null);
_this.getRenderTargetTextures = function () {
_this._renderTargets.reset();
if (_materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
_this._renderTargets.push(_this._reflectionTexture);
}
_this.subSurface.fillRenderTargetTextures(_this._renderTargets);
return _this._renderTargets;
};
_this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_4__["BRDFTextureTools"].GetEnvironmentBRDFTexture(scene);
_this.subSurface = new _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"](_this._markAllSubMeshesAsTexturesDirty.bind(_this), _this._markScenePrePassDirty.bind(_this), scene);
return _this;
}
Object.defineProperty(PBRBaseMaterial.prototype, "realTimeFiltering", {
/**
* Enables realtime filtering on the texture.
*/
get: function () {
return this._realTimeFiltering;
},
set: function (b) {
this._realTimeFiltering = b;
this.markAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_22__["Constants"].MATERIAL_TextureDirtyFlag);
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRBaseMaterial.prototype, "realTimeFilteringQuality", {
/**
* Quality switch for realtime filtering
*/
get: function () {
return this._realTimeFilteringQuality;
},
set: function (n) {
this._realTimeFilteringQuality = n;
this.markAsDirty(_Engines_constants__WEBPACK_IMPORTED_MODULE_22__["Constants"].MATERIAL_TextureDirtyFlag);
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRBaseMaterial.prototype, "canRenderToMRT", {
/**
* Can this material render to several textures at once
*/
get: function () {
return true;
},
enumerable: false,
configurable: true
});
/**
* Attaches a new image processing configuration to the PBR Material.
* @param configuration
*/
PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
var _this = this;
if (configuration === this._imageProcessingConfiguration) {
return;
}
// Detaches observer.
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
// Pick the scene configuration if needed.
if (!configuration) {
this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
}
else {
this._imageProcessingConfiguration = configuration;
}
// Attaches observer.
if (this._imageProcessingConfiguration) {
this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function () {
_this._markAllSubMeshesAsImageProcessingDirty();
});
}
};
Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
/**
* Gets a boolean indicating that current material needs to register RTT
*/
get: function () {
if (_materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
return true;
}
return this.subSurface.hasRenderTargetTextures();
},
enumerable: false,
configurable: true
});
/**
* Gets the name of the material class.
*/
PBRBaseMaterial.prototype.getClassName = function () {
return "PBRBaseMaterial";
};
Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
/**
* Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
*/
get: function () {
return this._useLogarithmicDepth;
},
/**
* Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
*/
set: function (value) {
this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
/**
* Returns true if alpha blending should be disabled.
*/
get: function () {
return (this.subSurface.disableAlphaBlending ||
this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_OPAQUE ||
this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);
},
enumerable: false,
configurable: true
});
/**
* Specifies whether or not this material should be rendered in alpha blend mode.
*/
PBRBaseMaterial.prototype.needAlphaBlending = function () {
if (this._disableAlphaBlending) {
return false;
}
return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
};
/**
* Specifies whether or not this material should be rendered in alpha test mode.
*/
PBRBaseMaterial.prototype.needAlphaTesting = function () {
if (this._forceAlphaTest) {
return true;
}
if (this.subSurface.disableAlphaBlending) {
return false;
}
return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === PBRBaseMaterial.PBRMATERIAL_ALPHATEST);
};
/**
* Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
*/
PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE;
};
/**
* Gets the texture used for the alpha test.
*/
PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
return this._albedoTexture;
};
/**
* Specifies that the submesh is ready to be used.
* @param mesh - BJS mesh.
* @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
* @param useInstances - Specifies that instances should be used.
* @returns - boolean indicating that the submesh is ready or not.
*/
PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
if (subMesh.effect && this.isFrozen) {
if (subMesh.effect._wasPreviouslyReady) {
return true;
}
}
if (!subMesh._materialDefines) {
subMesh._materialDefines = new PBRMaterialDefines();
}
var defines = subMesh._materialDefines;
if (this._isReadyForSubMesh(subMesh)) {
return true;
}
var scene = this.getScene();
var engine = scene.getEngine();
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].DiffuseTextureEnabled) {
if (!this._albedoTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].AmbientTextureEnabled) {
if (!this._ambientTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].OpacityTextureEnabled) {
if (!this._opacityTexture.isReadyOrNotBlocking()) {
return false;
}
}
var reflectionTexture = this._getReflectionTexture();
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled) {
if (!reflectionTexture.isReadyOrNotBlocking()) {
return false;
}
if (reflectionTexture.irradianceTexture && !reflectionTexture.irradianceTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].LightmapTextureEnabled) {
if (!this._lightmapTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].EmissiveTextureEnabled) {
if (!this._emissiveTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (_materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].SpecularTextureEnabled) {
if (this._metallicTexture) {
if (!this._metallicTexture.isReadyOrNotBlocking()) {
return false;
}
}
else if (this._reflectivityTexture) {
if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._metallicReflectanceTexture) {
if (!this._metallicReflectanceTexture.isReadyOrNotBlocking()) {
return false;
}
}
if (this._microSurfaceTexture) {
if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
return false;
}
}
}
if (engine.getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) {
// Bump texture cannot be not blocking.
if (!this._bumpTexture.isReady()) {
return false;
}
}
if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled) {
// This is blocking.
if (!this._environmentBRDFTexture.isReady()) {
return false;
}
}
}
}
if (!this.subSurface.isReadyForSubMesh(defines, scene) ||
!this.clearCoat.isReadyForSubMesh(defines, scene, engine, this._disableBumpMap) ||
!this.sheen.isReadyForSubMesh(defines, scene) ||
!this.anisotropy.isReadyForSubMesh(defines, scene) ||
!this.detailMap.isReadyForSubMesh(defines, scene)) {
return false;
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
if (!this._imageProcessingConfiguration.isReady()) {
return false;
}
}
if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind)) {
mesh.createNormals(true);
_Misc_logger__WEBPACK_IMPORTED_MODULE_2__["Logger"].Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
}
var previousEffect = subMesh.effect;
var lightDisposed = defines._areLightsDisposed;
var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances, null, subMesh.getRenderingMesh().hasThinInstances);
if (effect) {
if (this._onEffectCreatedObservable) {
onCreatedEffectParameters.effect = effect;
onCreatedEffectParameters.subMesh = subMesh;
this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
}
// Use previous effect while new one is compiling
if (this.allowShaderHotSwapping && previousEffect && !effect.isReady()) {
effect = previousEffect;
this._rebuildInParallel = true;
defines.markAsUnprocessed();
if (lightDisposed) {
// re register in case it takes more than one frame.
defines._areLightsDisposed = true;
return false;
}
}
else {
this._rebuildInParallel = false;
scene.resetCachedMaterial();
subMesh.setEffect(effect, defines);
this.buildUniformLayout();
}
}
if (!subMesh.effect || !subMesh.effect.isReady()) {
return false;
}
defines._renderId = scene.getRenderId();
subMesh.effect._wasPreviouslyReady = true;
return true;
};
/**
* Specifies if the material uses metallic roughness workflow.
* @returns boolean specifiying if the material uses metallic roughness workflow.
*/
PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
if (this._metallic != null || this._roughness != null || this._metallicTexture) {
return true;
}
return false;
};
PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane, useThinInstances) {
if (onCompiled === void 0) { onCompiled = null; }
if (onError === void 0) { onError = null; }
if (useInstances === void 0) { useInstances = null; }
if (useClipPlane === void 0) { useClipPlane = null; }
this._prepareDefines(mesh, defines, useInstances, useClipPlane, useThinInstances);
if (!defines.isDirty) {
return null;
}
defines.markAsProcessed();
var scene = this.getScene();
var engine = scene.getEngine();
// Fallbacks
var fallbacks = new _effectFallbacks__WEBPACK_IMPORTED_MODULE_26__["EffectFallbacks"]();
var fallbackRank = 0;
if (defines.USESPHERICALINVERTEX) {
fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
}
if (defines.FOG) {
fallbacks.addFallback(fallbackRank, "FOG");
}
if (defines.SPECULARAA) {
fallbacks.addFallback(fallbackRank, "SPECULARAA");
}
if (defines.POINTSIZE) {
fallbacks.addFallback(fallbackRank, "POINTSIZE");
}
if (defines.LOGARITHMICDEPTH) {
fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
}
if (defines.PARALLAX) {
fallbacks.addFallback(fallbackRank, "PARALLAX");
}
if (defines.PARALLAXOCCLUSION) {
fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
}
fallbackRank = _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank);
fallbackRank = _pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank);
fallbackRank = _pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank);
fallbackRank = _pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddFallbacks(defines, fallbacks, fallbackRank);
if (defines.ENVIRONMENTBRDF) {
fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
}
if (defines.TANGENT) {
fallbacks.addFallback(fallbackRank++, "TANGENT");
}
if (defines.BUMP) {
fallbacks.addFallback(fallbackRank++, "BUMP");
}
fallbackRank = _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
if (defines.SPECULARTERM) {
fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
}
if (defines.USESPHERICALFROMREFLECTIONMAP) {
fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
}
if (defines.USEIRRADIANCEMAP) {
fallbacks.addFallback(fallbackRank++, "USEIRRADIANCEMAP");
}
if (defines.LIGHTMAP) {
fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
}
if (defines.NORMAL) {
fallbacks.addFallback(fallbackRank++, "NORMAL");
}
if (defines.AMBIENT) {
fallbacks.addFallback(fallbackRank++, "AMBIENT");
}
if (defines.EMISSIVE) {
fallbacks.addFallback(fallbackRank++, "EMISSIVE");
}
if (defines.VERTEXCOLOR) {
fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
}
if (defines.MORPHTARGETS) {
fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
}
if (defines.MULTIVIEW) {
fallbacks.addFallback(0, "MULTIVIEW");
}
//Attributes
var attribs = [_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].PositionKind];
if (defines.NORMAL) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind);
}
if (defines.TANGENT) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].TangentKind);
}
if (defines.UV1) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UVKind);
}
if (defines.UV2) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].UV2Kind);
}
if (defines.VERTEXCOLOR) {
attribs.push(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].ColorKind);
}
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareAttributesForInstances(attribs, defines);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareAttributesForMorphTargets(attribs, mesh, defines);
var shaderName = "pbr";
var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vMetallicReflectanceFactors", "vEmissiveColor", "visibility", "vReflectionColor",
"vFogInfos", "vFogColor", "pointSize",
"vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos", "vReflectionFilteringInfo", "vMetallicReflectanceInfos",
"vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos",
"mBones",
"vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "vClipPlane5", "vClipPlane6", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "metallicReflectanceMatrix",
"vLightingIntensity",
"logarithmicDepthConstant",
"vSphericalX", "vSphericalY", "vSphericalZ",
"vSphericalXX_ZZ", "vSphericalYY_ZZ", "vSphericalZZ",
"vSphericalXY", "vSphericalYZ", "vSphericalZX",
"vSphericalL00",
"vSphericalL1_1", "vSphericalL10", "vSphericalL11",
"vSphericalL2_2", "vSphericalL2_1", "vSphericalL20", "vSphericalL21", "vSphericalL22",
"vReflectionMicrosurfaceInfos",
"vTangentSpaceParams", "boneTextureWidth",
"vDebugMode"
];
var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
"bumpSampler", "lightmapSampler", "opacitySampler",
"reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh", "irradianceSampler",
"microSurfaceSampler", "environmentBrdfSampler", "boneSampler", "metallicReflectanceSampler"];
var uniformBuffers = ["Material", "Scene"];
_material_detailMapConfiguration__WEBPACK_IMPORTED_MODULE_27__["DetailMapConfiguration"].AddUniforms(uniforms);
_material_detailMapConfiguration__WEBPACK_IMPORTED_MODULE_27__["DetailMapConfiguration"].AddSamplers(samplers);
_pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddUniforms(uniforms);
_pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].AddSamplers(samplers);
_pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].AddUniforms(uniforms);
_pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].AddSamplers(samplers);
_pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddUniforms(uniforms);
_pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].AddSamplers(samplers);
_pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddUniforms(uniforms);
_pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].AddSamplers(samplers);
if (_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_15__["ImageProcessingConfiguration"]) {
_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_15__["ImageProcessingConfiguration"].PrepareUniforms(uniforms, defines);
_Materials_imageProcessingConfiguration__WEBPACK_IMPORTED_MODULE_15__["ImageProcessingConfiguration"].PrepareSamplers(samplers, defines);
}
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareUniformsAndSamplersList({
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: defines,
maxSimultaneousLights: this._maxSimultaneousLights
});
var csnrOptions = {};
if (this.customShaderNameResolve) {
shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines, attribs, csnrOptions);
}
var join = defines.toString();
return engine.createEffect(shaderName, {
attributes: attribs,
uniformsNames: uniforms,
uniformBuffersNames: uniformBuffers,
samplers: samplers,
defines: join,
fallbacks: fallbacks,
onCompiled: onCompiled,
onError: onError,
indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS },
processFinalCode: csnrOptions.processFinalCode,
multiTarget: defines.PREPASS
}, engine);
};
PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane, useThinInstances) {
if (useInstances === void 0) { useInstances = null; }
if (useClipPlane === void 0) { useClipPlane = null; }
if (useThinInstances === void 0) { useThinInstances = false; }
var scene = this.getScene();
var engine = scene.getEngine();
// Lights
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
defines._needNormals = true;
// Multiview
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMultiview(scene, defines);
// PrePass
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForPrePass(scene, defines, this.canRenderToMRT);
// Textures
defines.METALLICWORKFLOW = this.isMetallicWorkflow();
if (defines._areTexturesDirty) {
defines._needUVs = false;
if (scene.texturesEnabled) {
if (scene.getEngine().getCaps().textureLOD) {
defines.LODBASEDMICROSFURACE = true;
}
if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].DiffuseTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
defines.GAMMAALBEDO = this._albedoTexture.gammaSpace;
}
else {
defines.ALBEDO = false;
}
if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].AmbientTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
}
else {
defines.AMBIENT = false;
}
if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].OpacityTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
}
else {
defines.OPACITY = false;
}
var reflectionTexture = this._getReflectionTexture();
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled) {
defines.REFLECTION = true;
defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
defines.RGBDREFLECTION = reflectionTexture.isRGBD;
defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
defines.LINEARSPECULARREFLECTION = reflectionTexture.linearSpecularLOD;
if (this.realTimeFiltering && this.realTimeFilteringQuality > 0) {
defines.NUM_SAMPLES = "" + this.realTimeFilteringQuality;
if (engine.webGLVersion > 1) {
defines.NUM_SAMPLES = defines.NUM_SAMPLES + "u";
}
defines.REALTIME_FILTERING = true;
}
else {
defines.REALTIME_FILTERING = false;
}
if (reflectionTexture.coordinatesMode === _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].INVCUBIC_MODE) {
defines.INVERTCUBICMAP = true;
}
defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
defines.REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
switch (reflectionTexture.coordinatesMode) {
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].EXPLICIT_MODE:
defines.REFLECTIONMAP_EXPLICIT = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].PLANAR_MODE:
defines.REFLECTIONMAP_PLANAR = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].PROJECTION_MODE:
defines.REFLECTIONMAP_PROJECTION = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].SKYBOX_MODE:
defines.REFLECTIONMAP_SKYBOX = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].SPHERICAL_MODE:
defines.REFLECTIONMAP_SPHERICAL = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].FIXED_EQUIRECTANGULAR_MODE:
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
break;
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].CUBIC_MODE:
case _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].INVCUBIC_MODE:
default:
defines.REFLECTIONMAP_CUBIC = true;
defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
break;
}
if (reflectionTexture.coordinatesMode !== _Materials_Textures_texture__WEBPACK_IMPORTED_MODULE_20__["Texture"].SKYBOX_MODE) {
if (reflectionTexture.irradianceTexture) {
defines.USEIRRADIANCEMAP = true;
defines.USESPHERICALFROMREFLECTIONMAP = false;
}
// Assume using spherical polynomial if the reflection texture is a cube map
else if (reflectionTexture.isCube) {
defines.USESPHERICALFROMREFLECTIONMAP = true;
defines.USEIRRADIANCEMAP = false;
if (this._forceIrradianceInFragment || this.realTimeFiltering || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
defines.USESPHERICALINVERTEX = false;
}
else {
defines.USESPHERICALINVERTEX = true;
}
}
}
}
else {
defines.REFLECTION = false;
defines.REFLECTIONMAP_3D = false;
defines.REFLECTIONMAP_SPHERICAL = false;
defines.REFLECTIONMAP_PLANAR = false;
defines.REFLECTIONMAP_CUBIC = false;
defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
defines.REFLECTIONMAP_PROJECTION = false;
defines.REFLECTIONMAP_SKYBOX = false;
defines.REFLECTIONMAP_EXPLICIT = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
defines.INVERTCUBICMAP = false;
defines.USESPHERICALFROMREFLECTIONMAP = false;
defines.USEIRRADIANCEMAP = false;
defines.USESPHERICALINVERTEX = false;
defines.REFLECTIONMAP_OPPOSITEZ = false;
defines.LODINREFLECTIONALPHA = false;
defines.GAMMAREFLECTION = false;
defines.RGBDREFLECTION = false;
defines.LINEARSPECULARREFLECTION = false;
}
if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].LightmapTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
defines.RGBDLIGHTMAP = this._lightmapTexture.isRGBD;
}
else {
defines.LIGHTMAP = false;
}
if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].EmissiveTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
}
else {
defines.EMISSIVE = false;
}
if (_materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].SpecularTextureEnabled) {
if (this._metallicTexture) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
}
else if (this._reflectivityTexture) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
}
else {
defines.REFLECTIVITY = false;
}
if (this._metallicReflectanceTexture) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._metallicReflectanceTexture, defines, "METALLIC_REFLECTANCE");
}
else {
defines.METALLIC_REFLECTANCE = false;
}
if (this._microSurfaceTexture) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
}
else {
defines.MICROSURFACEMAP = false;
}
}
else {
defines.REFLECTIVITY = false;
defines.MICROSURFACEMAP = false;
}
if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
if (this._useParallax && this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].DiffuseTextureEnabled) {
defines.PARALLAX = true;
defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
}
else {
defines.PARALLAX = false;
}
defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
}
else {
defines.BUMP = false;
}
if (this._environmentBRDFTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled) {
defines.ENVIRONMENTBRDF = true;
// Not actual true RGBD, only the B chanel is encoded as RGBD for sheen.
defines.ENVIRONMENTBRDF_RGBD = this._environmentBRDFTexture.isRGBD;
}
else {
defines.ENVIRONMENTBRDF = false;
defines.ENVIRONMENTBRDF_RGBD = false;
}
if (this._shouldUseAlphaFromAlbedoTexture()) {
defines.ALPHAFROMALBEDO = true;
}
else {
defines.ALPHAFROMALBEDO = false;
}
}
defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
defines.USEPHYSICALLIGHTFALLOFF = false;
defines.USEGLTFLIGHTFALLOFF = false;
}
else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
defines.USEPHYSICALLIGHTFALLOFF = false;
defines.USEGLTFLIGHTFALLOFF = true;
}
else {
defines.USEPHYSICALLIGHTFALLOFF = true;
defines.USEGLTFLIGHTFALLOFF = false;
}
defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
if (!this.backFaceCulling && this._twoSidedLighting) {
defines.TWOSIDEDLIGHTING = true;
}
else {
defines.TWOSIDEDLIGHTING = false;
}
defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
}
if (defines._areTexturesDirty || defines._areMiscDirty) {
defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
defines.PREMULTIPLYALPHA = (this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_22__["Constants"].ALPHA_PREMULTIPLIED || this.alphaMode === _Engines_constants__WEBPACK_IMPORTED_MODULE_22__["Constants"].ALPHA_PREMULTIPLIED_PORTERDUFF);
defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
}
if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
this._imageProcessingConfiguration.prepareDefines(defines);
}
defines.FORCENORMALFORWARD = this._forceNormalForward;
defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
// Misc.
if (defines._areMiscDirty) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(_Meshes_buffer__WEBPACK_IMPORTED_MODULE_7__["VertexBuffer"].NormalKind));
defines.DEBUGMODE = this._debugMode;
}
// External config
this.detailMap.prepareDefines(defines, scene);
this.subSurface.prepareDefines(defines, scene);
this.clearCoat.prepareDefines(defines, scene);
this.anisotropy.prepareDefines(defines, mesh, scene);
this.brdf.prepareDefines(defines);
this.sheen.prepareDefines(defines, scene);
// Values that need to be evaluated on every frame
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane, useThinInstances);
// Attribs
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== PBRBaseMaterial.PBRMATERIAL_OPAQUE);
};
/**
* Force shader compilation
*/
PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
var _this = this;
var localOptions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ clipPlane: false, useInstances: false }, options);
var defines = new PBRMaterialDefines();
var effect = this._prepareEffect(mesh, defines, undefined, undefined, localOptions.useInstances, localOptions.clipPlane, mesh.hasThinInstances);
if (this._onEffectCreatedObservable) {
onCreatedEffectParameters.effect = effect;
onCreatedEffectParameters.subMesh = null;
this._onEffectCreatedObservable.notifyObservers(onCreatedEffectParameters);
}
if (effect.isReady()) {
if (onCompiled) {
onCompiled(this);
}
}
else {
effect.onCompileObservable.add(function () {
if (onCompiled) {
onCompiled(_this);
}
});
}
};
/**
* Initializes the uniform buffer layout for the shader.
*/
PBRBaseMaterial.prototype.buildUniformLayout = function () {
// Order is important !
var ubo = this._uniformBuffer;
ubo.addUniform("vAlbedoInfos", 2);
ubo.addUniform("vAmbientInfos", 4);
ubo.addUniform("vOpacityInfos", 2);
ubo.addUniform("vEmissiveInfos", 2);
ubo.addUniform("vLightmapInfos", 2);
ubo.addUniform("vReflectivityInfos", 3);
ubo.addUniform("vMicroSurfaceSamplerInfos", 2);
ubo.addUniform("vReflectionInfos", 2);
ubo.addUniform("vReflectionFilteringInfo", 2);
ubo.addUniform("vReflectionPosition", 3);
ubo.addUniform("vReflectionSize", 3);
ubo.addUniform("vBumpInfos", 3);
ubo.addUniform("albedoMatrix", 16);
ubo.addUniform("ambientMatrix", 16);
ubo.addUniform("opacityMatrix", 16);
ubo.addUniform("emissiveMatrix", 16);
ubo.addUniform("lightmapMatrix", 16);
ubo.addUniform("reflectivityMatrix", 16);
ubo.addUniform("microSurfaceSamplerMatrix", 16);
ubo.addUniform("bumpMatrix", 16);
ubo.addUniform("vTangentSpaceParams", 2);
ubo.addUniform("reflectionMatrix", 16);
ubo.addUniform("vReflectionColor", 3);
ubo.addUniform("vAlbedoColor", 4);
ubo.addUniform("vLightingIntensity", 4);
ubo.addUniform("vReflectionMicrosurfaceInfos", 3);
ubo.addUniform("pointSize", 1);
ubo.addUniform("vReflectivityColor", 4);
ubo.addUniform("vEmissiveColor", 3);
ubo.addUniform("visibility", 1);
ubo.addUniform("vMetallicReflectanceFactors", 4);
ubo.addUniform("vMetallicReflectanceInfos", 2);
ubo.addUniform("metallicReflectanceMatrix", 16);
_pbrClearCoatConfiguration__WEBPACK_IMPORTED_MODULE_8__["PBRClearCoatConfiguration"].PrepareUniformBuffer(ubo);
_pbrAnisotropicConfiguration__WEBPACK_IMPORTED_MODULE_9__["PBRAnisotropicConfiguration"].PrepareUniformBuffer(ubo);
_pbrSheenConfiguration__WEBPACK_IMPORTED_MODULE_11__["PBRSheenConfiguration"].PrepareUniformBuffer(ubo);
_pbrSubSurfaceConfiguration__WEBPACK_IMPORTED_MODULE_12__["PBRSubSurfaceConfiguration"].PrepareUniformBuffer(ubo);
_material_detailMapConfiguration__WEBPACK_IMPORTED_MODULE_27__["DetailMapConfiguration"].PrepareUniformBuffer(ubo);
ubo.create();
};
/**
* Unbinds the material from the mesh
*/
PBRBaseMaterial.prototype.unbind = function () {
if (this._activeEffect) {
var needFlag = false;
if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
this._activeEffect.setTexture("reflection2DSampler", null);
needFlag = true;
}
if (this.subSurface.unbind(this._activeEffect)) {
needFlag = true;
}
if (needFlag) {
this._markAllSubMeshesAsTexturesDirty();
}
}
_super.prototype.unbind.call(this);
};
/**
* Binds the submesh data.
* @param world - The world matrix.
* @param mesh - The BJS mesh.
* @param subMesh - A submesh of the BJS mesh.
*/
PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
var scene = this.getScene();
var defines = subMesh._materialDefines;
if (!defines) {
return;
}
var effect = subMesh.effect;
if (!effect) {
return;
}
this._activeEffect = effect;
// Matrices
if (!defines.INSTANCES || defines.THIN_INSTANCES) {
this.bindOnlyWorldMatrix(world);
}
// Normal Matrix
if (defines.OBJECTSPACE_NORMALMAP) {
world.toNormalMatrix(this._normalMatrix);
this.bindOnlyNormalMatrix(this._normalMatrix);
}
var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
// Bones
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindBonesParameters(mesh, this._activeEffect);
var reflectionTexture = null;
var ubo = this._uniformBuffer;
if (mustRebind) {
var engine = scene.getEngine();
ubo.bindToEffect(effect, "Material");
this.bindViewProjection(effect);
reflectionTexture = this._getReflectionTexture();
if (!ubo.useUbo || !this.isFrozen || !ubo.isSync) {
// Texture uniforms
if (scene.texturesEnabled) {
if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].DiffuseTextureEnabled) {
ubo.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._albedoTexture, ubo, "albedo");
}
if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].AmbientTextureEnabled) {
ubo.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._ambientTexture, ubo, "ambient");
}
if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].OpacityTextureEnabled) {
ubo.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._opacityTexture, ubo, "opacity");
}
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled) {
ubo.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
ubo.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
if (reflectionTexture.boundingBoxSize) {
var cubeTexture = reflectionTexture;
ubo.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
ubo.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
}
if (this.realTimeFiltering) {
var width = reflectionTexture.getSize().width;
ubo.updateFloat2("vReflectionFilteringInfo", width, _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_14__["Scalar"].Log2(width));
}
if (!defines.USEIRRADIANCEMAP) {
var polynomials = reflectionTexture.sphericalPolynomial;
if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
if (defines.SPHERICAL_HARMONICS) {
var preScaledHarmonics = polynomials.preScaledHarmonics;
this._activeEffect.setVector3("vSphericalL00", preScaledHarmonics.l00);
this._activeEffect.setVector3("vSphericalL1_1", preScaledHarmonics.l1_1);
this._activeEffect.setVector3("vSphericalL10", preScaledHarmonics.l10);
this._activeEffect.setVector3("vSphericalL11", preScaledHarmonics.l11);
this._activeEffect.setVector3("vSphericalL2_2", preScaledHarmonics.l2_2);
this._activeEffect.setVector3("vSphericalL2_1", preScaledHarmonics.l2_1);
this._activeEffect.setVector3("vSphericalL20", preScaledHarmonics.l20);
this._activeEffect.setVector3("vSphericalL21", preScaledHarmonics.l21);
this._activeEffect.setVector3("vSphericalL22", preScaledHarmonics.l22);
}
else {
this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
}
}
}
ubo.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
}
if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].EmissiveTextureEnabled) {
ubo.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._emissiveTexture, ubo, "emissive");
}
if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].LightmapTextureEnabled) {
ubo.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._lightmapTexture, ubo, "lightmap");
}
if (_materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].SpecularTextureEnabled) {
if (this._metallicTexture) {
ubo.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._metallicTexture, ubo, "reflectivity");
}
else if (this._reflectivityTexture) {
ubo.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._reflectivityTexture, ubo, "reflectivity");
}
if (this._metallicReflectanceTexture) {
ubo.updateFloat2("vMetallicReflectanceInfos", this._metallicReflectanceTexture.coordinatesIndex, this._metallicReflectanceTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._metallicReflectanceTexture, ubo, "metallicReflectance");
}
if (this._microSurfaceTexture) {
ubo.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._microSurfaceTexture, ubo, "microSurfaceSampler");
}
}
if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) {
ubo.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindTextureMatrix(this._bumpTexture, ubo, "bump");
if (scene._mirroredCameraPosition) {
ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
}
else {
ubo.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
}
}
}
// Point size
if (this.pointsCloud) {
ubo.updateFloat("pointSize", this.pointSize);
}
// Colors
if (defines.METALLICWORKFLOW) {
_Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["TmpColors"].Color3[0].r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
_Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["TmpColors"].Color3[0].g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
ubo.updateColor4("vReflectivityColor", _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["TmpColors"].Color3[0], 1);
var ior = this.subSurface.indexOfRefraction;
var outside_ior = 1; // consider air as clear coat and other layaers would remap in the shader.
// We are here deriving our default reflectance from a common value for none metallic surface.
// Based of the schlick fresnel approximation model
// for dielectrics.
var f0 = Math.pow((ior - outside_ior) / (ior + outside_ior), 2);
// Tweak the default F0 and F90 based on our given setup
this._metallicReflectanceColor.scaleToRef(f0 * this._metallicF0Factor, _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["TmpColors"].Color3[0]);
var metallicF90 = this._metallicF0Factor;
ubo.updateColor4("vMetallicReflectanceFactors", _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["TmpColors"].Color3[0], metallicF90);
}
else {
ubo.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
}
ubo.updateColor3("vEmissiveColor", _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].EmissiveTextureEnabled ? this._emissiveColor : _Maths_math_color__WEBPACK_IMPORTED_MODULE_13__["Color3"].BlackReadOnly);
ubo.updateColor3("vReflectionColor", this._reflectionColor);
if (!defines.SS_REFRACTION && this.subSurface.linkRefractionWithTransparency) {
ubo.updateColor4("vAlbedoColor", this._albedoColor, 1);
}
else {
ubo.updateColor4("vAlbedoColor", this._albedoColor, this.alpha);
}
// Misc
this._lightingInfos.x = this._directIntensity;
this._lightingInfos.y = this._emissiveIntensity;
this._lightingInfos.z = this._environmentIntensity * scene.environmentIntensity;
this._lightingInfos.w = this._specularIntensity;
ubo.updateVector4("vLightingIntensity", this._lightingInfos);
}
// Visibility
ubo.updateFloat("visibility", mesh.visibility);
// Textures
if (scene.texturesEnabled) {
if (this._albedoTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].DiffuseTextureEnabled) {
ubo.setTexture("albedoSampler", this._albedoTexture);
}
if (this._ambientTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].AmbientTextureEnabled) {
ubo.setTexture("ambientSampler", this._ambientTexture);
}
if (this._opacityTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].OpacityTextureEnabled) {
ubo.setTexture("opacitySampler", this._opacityTexture);
}
if (reflectionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].ReflectionTextureEnabled) {
if (defines.LODBASEDMICROSFURACE) {
ubo.setTexture("reflectionSampler", reflectionTexture);
}
else {
ubo.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
ubo.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
ubo.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
}
if (defines.USEIRRADIANCEMAP) {
ubo.setTexture("irradianceSampler", reflectionTexture.irradianceTexture);
}
}
if (defines.ENVIRONMENTBRDF) {
ubo.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
}
if (this._emissiveTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].EmissiveTextureEnabled) {
ubo.setTexture("emissiveSampler", this._emissiveTexture);
}
if (this._lightmapTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].LightmapTextureEnabled) {
ubo.setTexture("lightmapSampler", this._lightmapTexture);
}
if (_materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].SpecularTextureEnabled) {
if (this._metallicTexture) {
ubo.setTexture("reflectivitySampler", this._metallicTexture);
}
else if (this._reflectivityTexture) {
ubo.setTexture("reflectivitySampler", this._reflectivityTexture);
}
if (this._metallicReflectanceTexture) {
ubo.setTexture("metallicReflectanceSampler", this._metallicReflectanceTexture);
}
if (this._microSurfaceTexture) {
ubo.setTexture("microSurfaceSampler", this._microSurfaceTexture);
}
}
if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_21__["MaterialFlags"].BumpTextureEnabled && !this._disableBumpMap) {
ubo.setTexture("bumpSampler", this._bumpTexture);
}
}
this.detailMap.bindForSubMesh(ubo, scene, this.isFrozen);
this.subSurface.bindForSubMesh(ubo, scene, engine, this.isFrozen, defines.LODBASEDMICROSFURACE, this.realTimeFiltering);
this.clearCoat.bindForSubMesh(ubo, scene, engine, this._disableBumpMap, this.isFrozen, this._invertNormalMapX, this._invertNormalMapY);
this.anisotropy.bindForSubMesh(ubo, scene, this.isFrozen);
this.sheen.bindForSubMesh(ubo, scene, this.isFrozen);
// Clip plane
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindClipPlane(this._activeEffect, scene);
// Colors
scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
effect.setColor3("vAmbientColor", this._globalAmbientColor);
effect.setFloat2("vDebugMode", this.debugLimit, this.debugFactor);
}
if (mustRebind || !this.isFrozen) {
// Lights
if (scene.lightsEnabled && !this._disableLighting) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._rebuildInParallel);
}
// View
if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== _scene__WEBPACK_IMPORTED_MODULE_5__["Scene"].FOGMODE_NONE || reflectionTexture) {
this.bindView(effect);
}
// Fog
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindFogParameters(scene, mesh, this._activeEffect, true);
// Morph targets
if (defines.NUM_MORPH_INFLUENCERS) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindMorphTargetParameters(mesh, this._activeEffect);
}
// image processing
this._imageProcessingConfiguration.bind(this._activeEffect);
// Log. depth
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_19__["MaterialHelper"].BindLogDepth(defines, this._activeEffect, scene);
}
ubo.update();
this._afterBind(mesh, this._activeEffect);
};
/**
* Returns the animatable textures.
* @returns - Array of animatable textures.
*/
PBRBaseMaterial.prototype.getAnimatables = function () {
var results = [];
if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
results.push(this._albedoTexture);
}
if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
results.push(this._ambientTexture);
}
if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
results.push(this._opacityTexture);
}
if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
results.push(this._reflectionTexture);
}
if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
results.push(this._emissiveTexture);
}
if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
results.push(this._metallicTexture);
}
else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
results.push(this._reflectivityTexture);
}
if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
results.push(this._bumpTexture);
}
if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
results.push(this._lightmapTexture);
}
this.detailMap.getAnimatables(results);
this.subSurface.getAnimatables(results);
this.clearCoat.getAnimatables(results);
this.sheen.getAnimatables(results);
this.anisotropy.getAnimatables(results);
return results;
};
/**
* Returns the texture used for reflections.
* @returns - Reflection texture if present. Otherwise, returns the environment texture.
*/
PBRBaseMaterial.prototype._getReflectionTexture = function () {
if (this._reflectionTexture) {
return this._reflectionTexture;
}
return this.getScene().environmentTexture;
};
/**
* Returns an array of the actively used textures.
* @returns - Array of BaseTextures
*/
PBRBaseMaterial.prototype.getActiveTextures = function () {
var activeTextures = _super.prototype.getActiveTextures.call(this);
if (this._albedoTexture) {
activeTextures.push(this._albedoTexture);
}
if (this._ambientTexture) {
activeTextures.push(this._ambientTexture);
}
if (this._opacityTexture) {
activeTextures.push(this._opacityTexture);
}
if (this._reflectionTexture) {
activeTextures.push(this._reflectionTexture);
}
if (this._emissiveTexture) {
activeTextures.push(this._emissiveTexture);
}
if (this._reflectivityTexture) {
activeTextures.push(this._reflectivityTexture);
}
if (this._metallicTexture) {
activeTextures.push(this._metallicTexture);
}
if (this._metallicReflectanceTexture) {
activeTextures.push(this._metallicReflectanceTexture);
}
if (this._microSurfaceTexture) {
activeTextures.push(this._microSurfaceTexture);
}
if (this._bumpTexture) {
activeTextures.push(this._bumpTexture);
}
if (this._lightmapTexture) {
activeTextures.push(this._lightmapTexture);
}
this.detailMap.getActiveTextures(activeTextures);
this.subSurface.getActiveTextures(activeTextures);
this.clearCoat.getActiveTextures(activeTextures);
this.sheen.getActiveTextures(activeTextures);
this.anisotropy.getActiveTextures(activeTextures);
return activeTextures;
};
/**
* Checks to see if a texture is used in the material.
* @param texture - Base texture to use.
* @returns - Boolean specifying if a texture is used in the material.
*/
PBRBaseMaterial.prototype.hasTexture = function (texture) {
if (_super.prototype.hasTexture.call(this, texture)) {
return true;
}
if (this._albedoTexture === texture) {
return true;
}
if (this._ambientTexture === texture) {
return true;
}
if (this._opacityTexture === texture) {
return true;
}
if (this._reflectionTexture === texture) {
return true;
}
if (this._reflectivityTexture === texture) {
return true;
}
if (this._metallicTexture === texture) {
return true;
}
if (this._metallicReflectanceTexture === texture) {
return true;
}
if (this._microSurfaceTexture === texture) {
return true;
}
if (this._bumpTexture === texture) {
return true;
}
if (this._lightmapTexture === texture) {
return true;
}
return this.detailMap.hasTexture(texture) ||
this.subSurface.hasTexture(texture) ||
this.clearCoat.hasTexture(texture) ||
this.sheen.hasTexture(texture) ||
this.anisotropy.hasTexture(texture);
};
/**
* Sets the required values to the prepass renderer.
* @param prePassRenderer defines the prepass renderer to setup
*/
PBRBaseMaterial.prototype.setPrePassRenderer = function (prePassRenderer) {
if (this.subSurface.isScatteringEnabled) {
prePassRenderer.subSurfaceConfiguration.enabled = true;
prePassRenderer.materialsShouldRenderIrradiance = true;
}
return true;
};
/**
* Disposes the resources of the material.
* @param forceDisposeEffect - Forces the disposal of effects.
* @param forceDisposeTextures - Forces the disposal of all textures.
*/
PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
if (forceDisposeTextures) {
if (this._environmentBRDFTexture && this.getScene().environmentBRDFTexture !== this._environmentBRDFTexture) {
this._environmentBRDFTexture.dispose();
}
(_a = this._albedoTexture) === null || _a === void 0 ? void 0 : _a.dispose();
(_b = this._ambientTexture) === null || _b === void 0 ? void 0 : _b.dispose();
(_c = this._opacityTexture) === null || _c === void 0 ? void 0 : _c.dispose();
(_d = this._reflectionTexture) === null || _d === void 0 ? void 0 : _d.dispose();
(_e = this._emissiveTexture) === null || _e === void 0 ? void 0 : _e.dispose();
(_f = this._metallicTexture) === null || _f === void 0 ? void 0 : _f.dispose();
(_g = this._reflectivityTexture) === null || _g === void 0 ? void 0 : _g.dispose();
(_h = this._bumpTexture) === null || _h === void 0 ? void 0 : _h.dispose();
(_j = this._lightmapTexture) === null || _j === void 0 ? void 0 : _j.dispose();
(_k = this._metallicReflectanceTexture) === null || _k === void 0 ? void 0 : _k.dispose();
(_l = this._microSurfaceTexture) === null || _l === void 0 ? void 0 : _l.dispose();
}
this.detailMap.dispose(forceDisposeTextures);
this.subSurface.dispose(forceDisposeTextures);
this.clearCoat.dispose(forceDisposeTextures);
this.sheen.dispose(forceDisposeTextures);
this.anisotropy.dispose(forceDisposeTextures);
this._renderTargets.dispose();
if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
}
_super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
};
/**
* PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
*/
PBRBaseMaterial.PBRMATERIAL_OPAQUE = _Materials_material__WEBPACK_IMPORTED_MODULE_16__["Material"].MATERIAL_OPAQUE;
/**
* PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
*/
PBRBaseMaterial.PBRMATERIAL_ALPHATEST = _Materials_material__WEBPACK_IMPORTED_MODULE_16__["Material"].MATERIAL_ALPHATEST;
/**
* PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
*/
PBRBaseMaterial.PBRMATERIAL_ALPHABLEND = _Materials_material__WEBPACK_IMPORTED_MODULE_16__["Material"].MATERIAL_ALPHABLEND;
/**
* PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
* They are also discarded below the alpha cutoff threshold to improve performances.
*/
PBRBaseMaterial.PBRMATERIAL_ALPHATESTANDBLEND = _Materials_material__WEBPACK_IMPORTED_MODULE_16__["Material"].MATERIAL_ALPHATESTANDBLEND;
/**
* Defines the default value of how much AO map is occluding the analytical lights
* (point spot...).
*/
PBRBaseMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 0;
/**
* PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
*/
PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
/**
* PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
* to enhance interoperability with other engines.
*/
PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
/**
* PBRMaterialLightFalloff Standard: light is falling off like in the standard material
* to enhance interoperability with other materials.
*/
PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsImageProcessingConfiguration"])()
], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty")
], PBRBaseMaterial.prototype, "debugMode", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
return PBRBaseMaterial;
}(_Materials_pushMaterial__WEBPACK_IMPORTED_MODULE_18__["PushMaterial"]));
/***/ }),
/***/ "./Materials/PBR/pbrBaseSimpleMaterial.ts":
/*!************************************************!*\
!*** ./Materials/PBR/pbrBaseSimpleMaterial.ts ***!
\************************************************/
/*! exports provided: PBRBaseSimpleMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRBaseSimpleMaterial", function() { return PBRBaseSimpleMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts");
/**
* The Physically based simple base material of BJS.
*
* This enables better naming and convention enforcements on top of the pbrMaterial.
* It is used as the base class for both the specGloss and metalRough conventions.
*/
var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRBaseSimpleMaterial, _super);
/**
* Instantiates a new PBRMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRBaseSimpleMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this.maxSimultaneousLights = 4;
/**
* If sets to true, disables all the lights affecting the material.
*/
_this.disableLighting = false;
/**
* If sets to true, x component of normal map value will invert (x = 1.0 - x).
*/
_this.invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will invert (y = 1.0 - y).
*/
_this.invertNormalMapY = false;
/**
* Emissivie color used to self-illuminate the model.
*/
_this.emissiveColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"](0, 0, 0);
/**
* Occlusion Channel Strenght.
*/
_this.occlusionStrength = 1.0;
/**
* If true, the light map contains occlusion information instead of lighting info.
*/
_this.useLightmapAsShadowmap = false;
_this._useAlphaFromAlbedoTexture = true;
_this._useAmbientInGrayScale = true;
return _this;
}
Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
/**
* Gets the current double sided mode.
*/
get: function () {
return this._twoSidedLighting;
},
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
set: function (value) {
if (this._twoSidedLighting === value) {
return;
}
this._twoSidedLighting = value;
this.backFaceCulling = !value;
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: false,
configurable: true
});
PBRBaseSimpleMaterial.prototype.getClassName = function () {
return "PBRBaseSimpleMaterial";
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("emissive"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", null)
], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
return PBRBaseSimpleMaterial;
}(_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_3__["PBRBaseMaterial"]));
/***/ }),
/***/ "./Materials/PBR/pbrClearCoatConfiguration.ts":
/*!****************************************************!*\
!*** ./Materials/PBR/pbrClearCoatConfiguration.ts ***!
\****************************************************/
/*! exports provided: PBRClearCoatConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRClearCoatConfiguration", function() { return PBRClearCoatConfiguration; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/**
* Define the code related to the clear coat parameters of the pbr material.
*/
var PBRClearCoatConfiguration = /** @class */ (function () {
/**
* Instantiate a new istance of clear coat configuration.
* @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty
*/
function PBRClearCoatConfiguration(markAllSubMeshesAsTexturesDirty) {
this._isEnabled = false;
/**
* Defines if the clear coat is enabled in the material.
*/
this.isEnabled = false;
/**
* Defines the clear coat layer strength (between 0 and 1) it defaults to 1.
*/
this.intensity = 1;
/**
* Defines the clear coat layer roughness.
*/
this.roughness = 0;
this._indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;
/**
* Defines the index of refraction of the clear coat.
* This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence
* The default fits with a polyurethane material.
* Changing the default value is more performance intensive.
*/
this.indexOfRefraction = PBRClearCoatConfiguration._DefaultIndexOfRefraction;
this._texture = null;
/**
* Stores the clear coat values in a texture.
*/
this.texture = null;
this._bumpTexture = null;
/**
* Define the clear coat specific bump texture.
*/
this.bumpTexture = null;
this._isTintEnabled = false;
/**
* Defines if the clear coat tint is enabled in the material.
*/
this.isTintEnabled = false;
/**
* Defines the clear coat tint of the material.
* This is only use if tint is enabled
*/
this.tintColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"].White();
/**
* Defines the distance at which the tint color should be found in the
* clear coat media.
* This is only use if tint is enabled
*/
this.tintColorAtDistance = 1;
/**
* Defines the clear coat layer thickness.
* This is only use if tint is enabled
*/
this.tintThickness = 1;
this._tintTexture = null;
/**
* Stores the clear tint values in a texture.
* rgb is tint
* a is a thickness factor
*/
this.tintTexture = null;
this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty;
}
/** @hidden */
PBRClearCoatConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () {
this._internalMarkAllSubMeshesAsTexturesDirty();
};
/**
* Gets wehter the submesh is ready to be used or not.
* @param defines the list of "defines" to update.
* @param scene defines the scene the material belongs to.
* @param engine defines the engine the material belongs to.
* @param disableBumpMap defines wether the material disables bump or not.
* @returns - boolean indicating that the submesh is ready or not.
*/
PBRClearCoatConfiguration.prototype.isReadyForSubMesh = function (defines, scene, engine, disableBumpMap) {
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) {
if (!this._texture.isReadyOrNotBlocking()) {
return false;
}
}
if (engine.getCaps().standardDerivatives && this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled && !disableBumpMap) {
// Bump texture cannot be not blocking.
if (!this._bumpTexture.isReady()) {
return false;
}
}
if (this._isTintEnabled && this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) {
if (!this._tintTexture.isReadyOrNotBlocking()) {
return false;
}
}
}
}
return true;
};
/**
* Checks to see if a texture is used in the material.
* @param defines the list of "defines" to update.
* @param scene defines the scene to the material belongs to.
*/
PBRClearCoatConfiguration.prototype.prepareDefines = function (defines, scene) {
if (this._isEnabled) {
defines.CLEARCOAT = true;
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "CLEARCOAT_TEXTURE");
}
else {
defines.CLEARCOAT_TEXTURE = false;
}
if (this._bumpTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._bumpTexture, defines, "CLEARCOAT_BUMP");
}
else {
defines.CLEARCOAT_BUMP = false;
}
defines.CLEARCOAT_DEFAULTIOR = this._indexOfRefraction === PBRClearCoatConfiguration._DefaultIndexOfRefraction;
if (this._isTintEnabled) {
defines.CLEARCOAT_TINT = true;
if (this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._tintTexture, defines, "CLEARCOAT_TINT_TEXTURE");
}
else {
defines.CLEARCOAT_TINT_TEXTURE = false;
}
}
else {
defines.CLEARCOAT_TINT = false;
defines.CLEARCOAT_TINT_TEXTURE = false;
}
}
}
}
else {
defines.CLEARCOAT = false;
defines.CLEARCOAT_TEXTURE = false;
defines.CLEARCOAT_BUMP = false;
defines.CLEARCOAT_TINT = false;
defines.CLEARCOAT_TINT_TEXTURE = false;
}
};
/**
* Binds the material data.
* @param uniformBuffer defines the Uniform buffer to fill in.
* @param scene defines the scene the material belongs to.
* @param engine defines the engine the material belongs to.
* @param disableBumpMap defines wether the material disables bump or not.
* @param isFrozen defines wether the material is frozen or not.
* @param invertNormalMapX If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
* @param invertNormalMapY If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
*/
PBRClearCoatConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, engine, disableBumpMap, isFrozen, invertNormalMapX, invertNormalMapY) {
if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) {
uniformBuffer.updateFloat2("vClearCoatInfos", this._texture.coordinatesIndex, this._texture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "clearCoat");
}
if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled && !disableBumpMap) {
uniformBuffer.updateFloat2("vClearCoatBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._bumpTexture, uniformBuffer, "clearCoatBump");
if (scene._mirroredCameraPosition) {
uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? 1.0 : -1.0, invertNormalMapY ? 1.0 : -1.0);
}
else {
uniformBuffer.updateFloat2("vClearCoatTangentSpaceParams", invertNormalMapX ? -1.0 : 1.0, invertNormalMapY ? -1.0 : 1.0);
}
}
if (this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) {
uniformBuffer.updateFloat2("vClearCoatTintInfos", this._tintTexture.coordinatesIndex, this._tintTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._tintTexture, uniformBuffer, "clearCoatTint");
}
// Clear Coat General params
uniformBuffer.updateFloat2("vClearCoatParams", this.intensity, this.roughness);
// Clear Coat Refraction params
var a = 1 - this._indexOfRefraction;
var b = 1 + this._indexOfRefraction;
var f0 = Math.pow((-a / b), 2); // Schlicks approx: (ior1 - ior2) / (ior1 + ior2) where ior2 for air is close to vacuum = 1.
var eta = 1 / this._indexOfRefraction;
uniformBuffer.updateFloat4("vClearCoatRefractionParams", f0, eta, a, b);
if (this._isTintEnabled) {
uniformBuffer.updateFloat4("vClearCoatTintParams", this.tintColor.r, this.tintColor.g, this.tintColor.b, Math.max(0.00001, this.tintThickness));
uniformBuffer.updateFloat("clearCoatColorAtDistance", Math.max(0.00001, this.tintColorAtDistance));
}
}
// Textures
if (scene.texturesEnabled) {
if (this._texture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTextureEnabled) {
uniformBuffer.setTexture("clearCoatSampler", this._texture);
}
if (this._bumpTexture && engine.getCaps().standardDerivatives && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatBumpTextureEnabled && !disableBumpMap) {
uniformBuffer.setTexture("clearCoatBumpSampler", this._bumpTexture);
}
if (this._isTintEnabled && this._tintTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ClearCoatTintTextureEnabled) {
uniformBuffer.setTexture("clearCoatTintSampler", this._tintTexture);
}
}
};
/**
* Checks to see if a texture is used in the material.
* @param texture - Base texture to use.
* @returns - Boolean specifying if a texture is used in the material.
*/
PBRClearCoatConfiguration.prototype.hasTexture = function (texture) {
if (this._texture === texture) {
return true;
}
if (this._bumpTexture === texture) {
return true;
}
if (this._tintTexture === texture) {
return true;
}
return false;
};
/**
* Returns an array of the actively used textures.
* @param activeTextures Array of BaseTextures
*/
PBRClearCoatConfiguration.prototype.getActiveTextures = function (activeTextures) {
if (this._texture) {
activeTextures.push(this._texture);
}
if (this._bumpTexture) {
activeTextures.push(this._bumpTexture);
}
if (this._tintTexture) {
activeTextures.push(this._tintTexture);
}
};
/**
* Returns the animatable textures.
* @param animatables Array of animatable textures.
*/
PBRClearCoatConfiguration.prototype.getAnimatables = function (animatables) {
if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
animatables.push(this._texture);
}
if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
animatables.push(this._bumpTexture);
}
if (this._tintTexture && this._tintTexture.animations && this._tintTexture.animations.length > 0) {
animatables.push(this._tintTexture);
}
};
/**
* Disposes the resources of the material.
* @param forceDisposeTextures - Forces the disposal of all textures.
*/
PBRClearCoatConfiguration.prototype.dispose = function (forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._texture) {
this._texture.dispose();
}
if (this._bumpTexture) {
this._bumpTexture.dispose();
}
if (this._tintTexture) {
this._tintTexture.dispose();
}
}
};
/**
* Get the current class name of the texture useful for serialization or dynamic coding.
* @returns "PBRClearCoatConfiguration"
*/
PBRClearCoatConfiguration.prototype.getClassName = function () {
return "PBRClearCoatConfiguration";
};
/**
* Add fallbacks to the effect fallbacks list.
* @param defines defines the Base texture to use.
* @param fallbacks defines the current fallback list.
* @param currentRank defines the current fallback rank.
* @returns the new fallback rank.
*/
PBRClearCoatConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) {
if (defines.CLEARCOAT_BUMP) {
fallbacks.addFallback(currentRank++, "CLEARCOAT_BUMP");
}
if (defines.CLEARCOAT_TINT) {
fallbacks.addFallback(currentRank++, "CLEARCOAT_TINT");
}
if (defines.CLEARCOAT) {
fallbacks.addFallback(currentRank++, "CLEARCOAT");
}
return currentRank;
};
/**
* Add the required uniforms to the current list.
* @param uniforms defines the current uniform list.
*/
PBRClearCoatConfiguration.AddUniforms = function (uniforms) {
uniforms.push("vClearCoatTangentSpaceParams", "vClearCoatParams", "vClearCoatRefractionParams", "vClearCoatTintParams", "clearCoatColorAtDistance", "clearCoatMatrix", "clearCoatBumpMatrix", "clearCoatTintMatrix", "vClearCoatInfos", "vClearCoatBumpInfos", "vClearCoatTintInfos");
};
/**
* Add the required samplers to the current list.
* @param samplers defines the current sampler list.
*/
PBRClearCoatConfiguration.AddSamplers = function (samplers) {
samplers.push("clearCoatSampler", "clearCoatBumpSampler", "clearCoatTintSampler");
};
/**
* Add the required uniforms to the current buffer.
* @param uniformBuffer defines the current uniform buffer.
*/
PBRClearCoatConfiguration.PrepareUniformBuffer = function (uniformBuffer) {
uniformBuffer.addUniform("vClearCoatParams", 2);
uniformBuffer.addUniform("vClearCoatRefractionParams", 4);
uniformBuffer.addUniform("vClearCoatInfos", 2);
uniformBuffer.addUniform("clearCoatMatrix", 16);
uniformBuffer.addUniform("vClearCoatBumpInfos", 2);
uniformBuffer.addUniform("vClearCoatTangentSpaceParams", 2);
uniformBuffer.addUniform("clearCoatBumpMatrix", 16);
uniformBuffer.addUniform("vClearCoatTintParams", 4);
uniformBuffer.addUniform("clearCoatColorAtDistance", 1);
uniformBuffer.addUniform("vClearCoatTintInfos", 2);
uniformBuffer.addUniform("clearCoatTintMatrix", 16);
};
/**
* Makes a duplicate of the current configuration into another one.
* @param clearCoatConfiguration define the config where to copy the info
*/
PBRClearCoatConfiguration.prototype.copyTo = function (clearCoatConfiguration) {
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return clearCoatConfiguration; }, this);
};
/**
* Serializes this clear coat configuration.
* @returns - An object with the serialized config.
*/
PBRClearCoatConfiguration.prototype.serialize = function () {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
};
/**
* Parses a anisotropy Configuration from a serialized object.
* @param source - Serialized object.
* @param scene Defines the scene we are parsing for
* @param rootUrl Defines the rootUrl to load from
*/
PBRClearCoatConfiguration.prototype.parse = function (source, scene, rootUrl) {
var _this = this;
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, scene, rootUrl);
};
/**
* This defaults to 1.5 corresponding to a 0.04 f0 or a 4% reflectance at normal incidence
* The default fits with a polyurethane material.
*/
PBRClearCoatConfiguration._DefaultIndexOfRefraction = 1.5;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "isEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRClearCoatConfiguration.prototype, "intensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRClearCoatConfiguration.prototype, "roughness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "indexOfRefraction", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "texture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "bumpTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "isTintEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], PBRClearCoatConfiguration.prototype, "tintColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRClearCoatConfiguration.prototype, "tintColorAtDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRClearCoatConfiguration.prototype, "tintThickness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRClearCoatConfiguration.prototype, "tintTexture", void 0);
return PBRClearCoatConfiguration;
}());
/***/ }),
/***/ "./Materials/PBR/pbrMaterial.ts":
/*!**************************************!*\
!*** ./Materials/PBR/pbrMaterial.ts ***!
\**************************************/
/*! exports provided: PBRMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMaterial", function() { return PBRMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Misc/brdfTextureTools */ "./Misc/brdfTextureTools.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./pbrBaseMaterial */ "./Materials/PBR/pbrBaseMaterial.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* The Physically based material of BJS.
*
* This offers the main features of a standard PBR material.
* For more information, please refer to the documentation :
* https://doc.babylonjs.com/how_to/physically_based_rendering
*/
var PBRMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRMaterial, _super);
/**
* Instantiates a new PBRMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
/**
* Intensity of the direct lights e.g. the four lights available in your scene.
* This impacts both the direct diffuse and specular highlights.
*/
_this.directIntensity = 1.0;
/**
* Intensity of the emissive part of the material.
* This helps controlling the emissive effect without modifying the emissive color.
*/
_this.emissiveIntensity = 1.0;
/**
* Intensity of the environment e.g. how much the environment will light the object
* either through harmonics for rough material or through the refelction for shiny ones.
*/
_this.environmentIntensity = 1.0;
/**
* This is a special control allowing the reduction of the specular highlights coming from the
* four lights of the scene. Those highlights may not be needed in full environment lighting.
*/
_this.specularIntensity = 1.0;
/**
* Debug Control allowing disabling the bump map on this material.
*/
_this.disableBumpMap = false;
/**
* AKA Occlusion Texture Intensity in other nomenclature.
*/
_this.ambientTextureStrength = 1.0;
/**
* Defines how much the AO map is occluding the analytical lights (point spot...).
* 1 means it completely occludes it
* 0 mean it has no impact
*/
_this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
/**
* In metallic workflow, specifies an F0 factor to help configuring the material F0.
* By default the indexOfrefraction is used to compute F0;
*
* This is used as a factor against the default reflectance at normal incidence to tweak it.
*
* F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor;
* F90 = metallicReflectanceColor;
*/
_this.metallicF0Factor = 1;
/**
* In metallic workflow, specifies an F90 color to help configuring the material F90.
* By default the F90 is always 1;
*
* Please note that this factor is also used as a factor against the default reflectance at normal incidence.
*
* F0 = defaultF0 * metallicF0Factor * metallicReflectanceColor
* F90 = metallicReflectanceColor;
*/
_this.metallicReflectanceColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"].White();
/**
* The color of a material in ambient lighting.
*/
_this.ambientColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0, 0, 0);
/**
* AKA Diffuse Color in other nomenclature.
*/
_this.albedoColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](1, 1, 1);
/**
* AKA Specular Color in other nomenclature.
*/
_this.reflectivityColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](1, 1, 1);
/**
* The color reflected from the material.
*/
_this.reflectionColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](1.0, 1.0, 1.0);
/**
* The color emitted from the material.
*/
_this.emissiveColor = new _Maths_math_color__WEBPACK_IMPORTED_MODULE_3__["Color3"](0, 0, 0);
/**
* AKA Glossiness in other nomenclature.
*/
_this.microSurface = 1.0;
/**
* If true, the light map contains occlusion information instead of lighting info.
*/
_this.useLightmapAsShadowmap = false;
/**
* Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
*/
_this.useAlphaFromAlbedoTexture = false;
/**
* Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
*/
_this.forceAlphaTest = false;
/**
* Defines the alpha limits in alpha test mode.
*/
_this.alphaCutOff = 0.4;
/**
* Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
*/
_this.useSpecularOverAlpha = true;
/**
* Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
*/
_this.useMicroSurfaceFromReflectivityMapAlpha = false;
/**
* Specifies if the metallic texture contains the roughness information in its alpha channel.
*/
_this.useRoughnessFromMetallicTextureAlpha = true;
/**
* Specifies if the metallic texture contains the roughness information in its green channel.
*/
_this.useRoughnessFromMetallicTextureGreen = false;
/**
* Specifies if the metallic texture contains the metallness information in its blue channel.
*/
_this.useMetallnessFromMetallicTextureBlue = false;
/**
* Specifies if the metallic texture contains the ambient occlusion information in its red channel.
*/
_this.useAmbientOcclusionFromMetallicTextureRed = false;
/**
* Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
*/
_this.useAmbientInGrayScale = false;
/**
* In case the reflectivity map does not contain the microsurface information in its alpha channel,
* The material will try to infer what glossiness each pixel should be.
*/
_this.useAutoMicroSurfaceFromReflectivityMap = false;
/**
* Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
* A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
*/
_this.useRadianceOverAlpha = true;
/**
* Allows using an object space normal map (instead of tangent space).
*/
_this.useObjectSpaceNormalMap = false;
/**
* Allows using the bump map in parallax mode.
*/
_this.useParallax = false;
/**
* Allows using the bump map in parallax occlusion mode.
*/
_this.useParallaxOcclusion = false;
/**
* Controls the scale bias of the parallax mode.
*/
_this.parallaxScaleBias = 0.05;
/**
* If sets to true, disables all the lights affecting the material.
*/
_this.disableLighting = false;
/**
* Force the shader to compute irradiance in the fragment shader in order to take bump in account.
*/
_this.forceIrradianceInFragment = false;
/**
* Number of Simultaneous lights allowed on the material.
*/
_this.maxSimultaneousLights = 4;
/**
* If sets to true, x component of normal map value will invert (x = 1.0 - x).
*/
_this.invertNormalMapX = false;
/**
* If sets to true, y component of normal map value will invert (y = 1.0 - y).
*/
_this.invertNormalMapY = false;
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
_this.twoSidedLighting = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
*/
_this.useAlphaFresnel = false;
/**
* A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
* And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
*/
_this.useLinearAlphaFresnel = false;
/**
* Let user defines the brdf lookup texture used for IBL.
* A default 8bit version is embedded but you could point at :
* * Default texture: https://assets.babylonjs.com/environments/correlatedMSBRDF_RGBD.png
* * Default 16bit pixel depth texture: https://assets.babylonjs.com/environments/correlatedMSBRDF.dds
* * LEGACY Default None correlated https://assets.babylonjs.com/environments/uncorrelatedBRDF_RGBD.png
* * LEGACY Default None correlated 16bit pixel depth https://assets.babylonjs.com/environments/uncorrelatedBRDF.dds
*/
_this.environmentBRDFTexture = null;
/**
* Force normal to face away from face.
*/
_this.forceNormalForward = false;
/**
* Enables specular anti aliasing in the PBR shader.
* It will both interacts on the Geometry for analytical and IBL lighting.
* It also prefilter the roughness map based on the bump values.
*/
_this.enableSpecularAntiAliasing = false;
/**
* This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
* makes the reflect vector face the model (under horizon).
*/
_this.useHorizonOcclusion = true;
/**
* This parameters will enable/disable radiance occlusion by preventing the radiance to lit
* too much the area relying on ambient texture to define their ambient occlusion.
*/
_this.useRadianceOcclusion = true;
/**
* If set to true, no lighting calculations will be applied.
*/
_this.unlit = false;
_this._environmentBRDFTexture = _Misc_brdfTextureTools__WEBPACK_IMPORTED_MODULE_2__["BRDFTextureTools"].GetEnvironmentBRDFTexture(scene);
return _this;
}
Object.defineProperty(PBRMaterial.prototype, "refractionTexture", {
/**
* Stores the refracted light information in a texture.
*/
get: function () {
return this.subSurface.refractionTexture;
},
set: function (value) {
this.subSurface.refractionTexture = value;
if (value) {
this.subSurface.isRefractionEnabled = true;
}
else if (!this.subSurface.linkRefractionWithTransparency) {
this.subSurface.isRefractionEnabled = false;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "indexOfRefraction", {
/**
* Index of refraction of the material base layer.
* https://en.wikipedia.org/wiki/List_of_refractive_indices
*
* This does not only impact refraction but also the Base F0 of Dielectric Materials.
*
* From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))
*/
get: function () {
return this.subSurface.indexOfRefraction;
},
set: function (value) {
this.subSurface.indexOfRefraction = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "invertRefractionY", {
/**
* Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
*/
get: function () {
return this.subSurface.invertRefractionY;
},
set: function (value) {
this.subSurface.invertRefractionY = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "linkRefractionWithTransparency", {
/**
* This parameters will make the material used its opacity to control how much it is refracting aginst not.
* Materials half opaque for instance using refraction could benefit from this control.
*/
get: function () {
return this.subSurface.linkRefractionWithTransparency;
},
set: function (value) {
this.subSurface.linkRefractionWithTransparency = value;
if (value) {
this.subSurface.isRefractionEnabled = true;
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
/**
* BJS is using an harcoded light falloff based on a manually sets up range.
* In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
* This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
*/
get: function () {
return this._lightFalloff === _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL;
},
/**
* BJS is using an harcoded light falloff based on a manually sets up range.
* In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
* This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
*/
set: function (value) {
if (value !== this.usePhysicalLightFalloff) {
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
if (value) {
this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_PHYSICAL;
}
else {
this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD;
}
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
/**
* In order to support the falloff compatibility with gltf, a special mode has been added
* to reproduce the gltf light falloff.
*/
get: function () {
return this._lightFalloff === _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF;
},
/**
* In order to support the falloff compatibility with gltf, a special mode has been added
* to reproduce the gltf light falloff.
*/
set: function (value) {
if (value !== this.useGLTFLightFalloff) {
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
if (value) {
this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_GLTF;
}
else {
this._lightFalloff = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].LIGHTFALLOFF_STANDARD;
}
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
/**
* Gets the image processing configuration used either in this material.
*/
get: function () {
return this._imageProcessingConfiguration;
},
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
set: function (value) {
this._attachImageProcessingConfiguration(value);
// Ensure the effect will be rebuilt.
this._markAllSubMeshesAsTexturesDirty();
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
/**
* Gets wether the color curves effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorCurvesEnabled;
},
/**
* Sets wether the color curves effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorCurvesEnabled = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
/**
* Gets wether the color grading effect is enabled.
*/
get: function () {
return this.imageProcessingConfiguration.colorGradingEnabled;
},
/**
* Gets wether the color grading effect is enabled.
*/
set: function (value) {
this.imageProcessingConfiguration.colorGradingEnabled = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
/**
* Gets wether tonemapping is enabled or not.
*/
get: function () {
return this._imageProcessingConfiguration.toneMappingEnabled;
},
/**
* Sets wether tonemapping is enabled or not
*/
set: function (value) {
this._imageProcessingConfiguration.toneMappingEnabled = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
get: function () {
return this._imageProcessingConfiguration.exposure;
},
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
set: function (value) {
this._imageProcessingConfiguration.exposure = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
/**
* Gets The camera contrast used on this material.
*/
get: function () {
return this._imageProcessingConfiguration.contrast;
},
/**
* Sets The camera contrast used on this material.
*/
set: function (value) {
this._imageProcessingConfiguration.contrast = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
/**
* Gets the Color Grading 2D Lookup Texture.
*/
get: function () {
return this._imageProcessingConfiguration.colorGradingTexture;
},
/**
* Sets the Color Grading 2D Lookup Texture.
*/
set: function (value) {
this._imageProcessingConfiguration.colorGradingTexture = value;
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
get: function () {
return this._imageProcessingConfiguration.colorCurves;
},
/**
* The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
* They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
* These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
* corresponding to low luminance, medium luminance, and high luminance areas respectively.
*/
set: function (value) {
this._imageProcessingConfiguration.colorCurves = value;
},
enumerable: false,
configurable: true
});
/**
* Returns the name of this material class.
*/
PBRMaterial.prototype.getClassName = function () {
return "PBRMaterial";
};
/**
* Makes a duplicate of the current material.
* @param name - name to use for the new material.
*/
PBRMaterial.prototype.clone = function (name) {
var _this = this;
var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
clone.id = name;
clone.name = name;
this.clearCoat.copyTo(clone.clearCoat);
this.anisotropy.copyTo(clone.anisotropy);
this.brdf.copyTo(clone.brdf);
this.sheen.copyTo(clone.sheen);
this.subSurface.copyTo(clone.subSurface);
return clone;
};
/**
* Serializes this PBR Material.
* @returns - An object with the serialized material.
*/
PBRMaterial.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.PBRMaterial";
serializationObject.clearCoat = this.clearCoat.serialize();
serializationObject.anisotropy = this.anisotropy.serialize();
serializationObject.brdf = this.brdf.serialize();
serializationObject.sheen = this.sheen.serialize();
serializationObject.subSurface = this.subSurface.serialize();
return serializationObject;
};
// Statics
/**
* Parses a PBR Material from a serialized object.
* @param source - Serialized object.
* @param scene - BJS scene instance.
* @param rootUrl - url for the scene object
* @returns - PBRMaterial
*/
PBRMaterial.Parse = function (source, scene, rootUrl) {
var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
if (source.clearCoat) {
material.clearCoat.parse(source.clearCoat, scene, rootUrl);
}
if (source.anisotropy) {
material.anisotropy.parse(source.anisotropy, scene, rootUrl);
}
if (source.brdf) {
material.brdf.parse(source.brdf, scene, rootUrl);
}
if (source.sheen) {
material.sheen.parse(source.sheen, scene, rootUrl);
}
if (source.subSurface) {
material.subSurface.parse(source.subSurface, scene, rootUrl);
}
return material;
};
/**
* PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
*/
PBRMaterial.PBRMATERIAL_OPAQUE = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_OPAQUE;
/**
* PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
*/
PBRMaterial.PBRMATERIAL_ALPHATEST = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHATEST;
/**
* PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
*/
PBRMaterial.PBRMATERIAL_ALPHABLEND = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHABLEND;
/**
* PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
* They are also discarded below the alpha cutoff threshold to improve performances.
*/
PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].PBRMATERIAL_ALPHATESTANDBLEND;
/**
* Defines the default value of how much AO map is occluding the analytical lights
* (point spot...).
*/
PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = _pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"].DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "directIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "environmentIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "specularIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "disableBumpMap", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "albedoTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTextureStrength", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "opacityTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectionTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectivityTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallic", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "roughness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicF0Factor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicReflectanceColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "metallicReflectanceTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "microSurfaceTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "bumpTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", null)
], PBRMaterial.prototype, "lightmapTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("ambient"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "ambientColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("albedo"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "albedoColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("reflectivity"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectivityColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("reflection"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "reflectionColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("emissive"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "emissiveColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "microSurface", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "forceAlphaTest", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesAndMiscDirty")
], PBRMaterial.prototype, "alphaCutOff", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRMaterial.prototype, "useGLTFLightFalloff", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useParallax", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "parallaxScaleBias", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], PBRMaterial.prototype, "disableLighting", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsLightsDirty")
], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertNormalMapX", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "invertNormalMapY", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "twoSidedLighting", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useAlphaFresnel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "forceNormalForward", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsMiscDirty")
], PBRMaterial.prototype, "unlit", void 0);
return PBRMaterial;
}(_pbrBaseMaterial__WEBPACK_IMPORTED_MODULE_4__["PBRBaseMaterial"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_5__["_TypeStore"].RegisteredTypes["BABYLON.PBRMaterial"] = PBRMaterial;
/***/ }),
/***/ "./Materials/PBR/pbrMetallicRoughnessMaterial.ts":
/*!*******************************************************!*\
!*** ./Materials/PBR/pbrMetallicRoughnessMaterial.ts ***!
\*******************************************************/
/*! exports provided: PBRMetallicRoughnessMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRMetallicRoughnessMaterial", function() { return PBRMetallicRoughnessMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* The PBR material of BJS following the metal roughness convention.
*
* This fits to the PBR convention in the GLTF definition:
* https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
*/
var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRMetallicRoughnessMaterial, _super);
/**
* Instantiates a new PBRMetalRoughnessMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRMetallicRoughnessMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._useRoughnessFromMetallicTextureAlpha = false;
_this._useRoughnessFromMetallicTextureGreen = true;
_this._useMetallnessFromMetallicTextureBlue = true;
_this.metallic = 1.0;
_this.roughness = 1.0;
return _this;
}
/**
* Return the currrent class name of the material.
*/
PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
return "PBRMetallicRoughnessMaterial";
};
/**
* Makes a duplicate of the current material.
* @param name - name to use for the new material.
*/
PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
var _this = this;
var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
clone.id = name;
clone.name = name;
this.clearCoat.copyTo(clone.clearCoat);
this.anisotropy.copyTo(clone.anisotropy);
this.brdf.copyTo(clone.brdf);
this.sheen.copyTo(clone.sheen);
this.subSurface.copyTo(clone.subSurface);
return clone;
};
/**
* Serialize the material to a parsable JSON object.
*/
PBRMetallicRoughnessMaterial.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
serializationObject.clearCoat = this.clearCoat.serialize();
serializationObject.anisotropy = this.anisotropy.serialize();
serializationObject.brdf = this.brdf.serialize();
serializationObject.sheen = this.sheen.serialize();
serializationObject.subSurface = this.subSurface.serialize();
return serializationObject;
};
/**
* Parses a JSON object correponding to the serialize function.
*/
PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
if (source.clearCoat) {
material.clearCoat.parse(source.clearCoat, scene, rootUrl);
}
if (source.anisotropy) {
material.anisotropy.parse(source.anisotropy, scene, rootUrl);
}
if (source.brdf) {
material.brdf.parse(source.brdf, scene, rootUrl);
}
if (source.sheen) {
material.sheen.parse(source.sheen, scene, rootUrl);
}
if (source.subSurface) {
material.subSurface.parse(source.subSurface, scene, rootUrl);
}
return material;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
return PBRMetallicRoughnessMaterial;
}(_pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRBaseSimpleMaterial"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.PBRMetallicRoughnessMaterial"] = PBRMetallicRoughnessMaterial;
/***/ }),
/***/ "./Materials/PBR/pbrSheenConfiguration.ts":
/*!************************************************!*\
!*** ./Materials/PBR/pbrSheenConfiguration.ts ***!
\************************************************/
/*! exports provided: PBRSheenConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSheenConfiguration", function() { return PBRSheenConfiguration; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Materials/materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/**
* Define the code related to the Sheen parameters of the pbr material.
*/
var PBRSheenConfiguration = /** @class */ (function () {
/**
* Instantiate a new istance of clear coat configuration.
* @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty
*/
function PBRSheenConfiguration(markAllSubMeshesAsTexturesDirty) {
this._isEnabled = false;
/**
* Defines if the material uses sheen.
*/
this.isEnabled = false;
this._linkSheenWithAlbedo = false;
/**
* Defines if the sheen is linked to the sheen color.
*/
this.linkSheenWithAlbedo = false;
/**
* Defines the sheen intensity.
*/
this.intensity = 1;
/**
* Defines the sheen color.
*/
this.color = _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"].White();
this._texture = null;
/**
* Stores the sheen tint values in a texture.
* rgb is tint
* a is a intensity or roughness if roughness has been defined
*/
this.texture = null;
this._roughness = null;
/**
* Defines the sheen roughness.
* It is not taken into account if linkSheenWithAlbedo is true.
* To stay backward compatible, material roughness is used instead if sheen roughness = null
*/
this.roughness = null;
this._albedoScaling = false;
/**
* If true, the sheen effect is layered above the base BRDF with the albedo-scaling technique.
* It allows the strength of the sheen effect to not depend on the base color of the material,
* making it easier to setup and tweak the effect
*/
this.albedoScaling = false;
this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty;
}
/** @hidden */
PBRSheenConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () {
this._internalMarkAllSubMeshesAsTexturesDirty();
};
/**
* Specifies that the submesh is ready to be used.
* @param defines the list of "defines" to update.
* @param scene defines the scene the material belongs to.
* @returns - boolean indicating that the submesh is ready or not.
*/
PBRSheenConfiguration.prototype.isReadyForSubMesh = function (defines, scene) {
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) {
if (!this._texture.isReadyOrNotBlocking()) {
return false;
}
}
}
}
return true;
};
/**
* Checks to see if a texture is used in the material.
* @param defines the list of "defines" to update.
* @param scene defines the scene the material belongs to.
*/
PBRSheenConfiguration.prototype.prepareDefines = function (defines, scene) {
if (this._isEnabled) {
defines.SHEEN = this._isEnabled;
defines.SHEEN_LINKWITHALBEDO = this._linkSheenWithAlbedo;
defines.SHEEN_ROUGHNESS = this._roughness !== null;
defines.SHEEN_ALBEDOSCALING = this._albedoScaling;
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._texture, defines, "SHEEN_TEXTURE");
}
else {
defines.SHEEN_TEXTURE = false;
}
}
}
}
else {
defines.SHEEN = false;
defines.SHEEN_TEXTURE = false;
defines.SHEEN_LINKWITHALBEDO = false;
defines.SHEEN_ROUGHNESS = false;
defines.SHEEN_ALBEDOSCALING = false;
}
};
/**
* Binds the material data.
* @param uniformBuffer defines the Uniform buffer to fill in.
* @param scene defines the scene the material belongs to.
* @param isFrozen defines wether the material is frozen or not.
*/
PBRSheenConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, isFrozen) {
if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) {
uniformBuffer.updateFloat2("vSheenInfos", this._texture.coordinatesIndex, this._texture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._texture, uniformBuffer, "sheen");
}
// Sheen
uniformBuffer.updateFloat4("vSheenColor", this.color.r, this.color.g, this.color.b, this.intensity);
if (this._roughness !== null) {
uniformBuffer.updateFloat("vSheenRoughness", this._roughness);
}
}
// Textures
if (scene.texturesEnabled) {
if (this._texture && _Materials_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].SheenTextureEnabled) {
uniformBuffer.setTexture("sheenSampler", this._texture);
}
}
};
/**
* Checks to see if a texture is used in the material.
* @param texture - Base texture to use.
* @returns - Boolean specifying if a texture is used in the material.
*/
PBRSheenConfiguration.prototype.hasTexture = function (texture) {
if (this._texture === texture) {
return true;
}
return false;
};
/**
* Returns an array of the actively used textures.
* @param activeTextures Array of BaseTextures
*/
PBRSheenConfiguration.prototype.getActiveTextures = function (activeTextures) {
if (this._texture) {
activeTextures.push(this._texture);
}
};
/**
* Returns the animatable textures.
* @param animatables Array of animatable textures.
*/
PBRSheenConfiguration.prototype.getAnimatables = function (animatables) {
if (this._texture && this._texture.animations && this._texture.animations.length > 0) {
animatables.push(this._texture);
}
};
/**
* Disposes the resources of the material.
* @param forceDisposeTextures - Forces the disposal of all textures.
*/
PBRSheenConfiguration.prototype.dispose = function (forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._texture) {
this._texture.dispose();
}
}
};
/**
* Get the current class name of the texture useful for serialization or dynamic coding.
* @returns "PBRSheenConfiguration"
*/
PBRSheenConfiguration.prototype.getClassName = function () {
return "PBRSheenConfiguration";
};
/**
* Add fallbacks to the effect fallbacks list.
* @param defines defines the Base texture to use.
* @param fallbacks defines the current fallback list.
* @param currentRank defines the current fallback rank.
* @returns the new fallback rank.
*/
PBRSheenConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) {
if (defines.SHEEN) {
fallbacks.addFallback(currentRank++, "SHEEN");
}
return currentRank;
};
/**
* Add the required uniforms to the current list.
* @param uniforms defines the current uniform list.
*/
PBRSheenConfiguration.AddUniforms = function (uniforms) {
uniforms.push("vSheenColor", "vSheenRoughness", "vSheenInfos", "sheenMatrix");
};
/**
* Add the required uniforms to the current buffer.
* @param uniformBuffer defines the current uniform buffer.
*/
PBRSheenConfiguration.PrepareUniformBuffer = function (uniformBuffer) {
uniformBuffer.addUniform("vSheenColor", 4);
uniformBuffer.addUniform("vSheenRoughness", 1);
uniformBuffer.addUniform("vSheenInfos", 2);
uniformBuffer.addUniform("sheenMatrix", 16);
};
/**
* Add the required samplers to the current list.
* @param samplers defines the current sampler list.
*/
PBRSheenConfiguration.AddSamplers = function (samplers) {
samplers.push("sheenSampler");
};
/**
* Makes a duplicate of the current configuration into another one.
* @param sheenConfiguration define the config where to copy the info
*/
PBRSheenConfiguration.prototype.copyTo = function (sheenConfiguration) {
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return sheenConfiguration; }, this);
};
/**
* Serializes this BRDF configuration.
* @returns - An object with the serialized config.
*/
PBRSheenConfiguration.prototype.serialize = function () {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
};
/**
* Parses a anisotropy Configuration from a serialized object.
* @param source - Serialized object.
* @param scene Defines the scene we are parsing for
* @param rootUrl Defines the rootUrl to load from
*/
PBRSheenConfiguration.prototype.parse = function (source, scene, rootUrl) {
var _this = this;
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, scene, rootUrl);
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "isEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "linkSheenWithAlbedo", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSheenConfiguration.prototype, "intensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], PBRSheenConfiguration.prototype, "color", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "texture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "roughness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSheenConfiguration.prototype, "albedoScaling", void 0);
return PBRSheenConfiguration;
}());
/***/ }),
/***/ "./Materials/PBR/pbrSpecularGlossinessMaterial.ts":
/*!********************************************************!*\
!*** ./Materials/PBR/pbrSpecularGlossinessMaterial.ts ***!
\********************************************************/
/*! exports provided: PBRSpecularGlossinessMaterial */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSpecularGlossinessMaterial", function() { return PBRSpecularGlossinessMaterial; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./pbrBaseSimpleMaterial */ "./Materials/PBR/pbrBaseSimpleMaterial.ts");
/* harmony import */ var _Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Misc/typeStore */ "./Misc/typeStore.ts");
/**
* The PBR material of BJS following the specular glossiness convention.
*
* This fits to the PBR convention in the GLTF definition:
* https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
*/
var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PBRSpecularGlossinessMaterial, _super);
/**
* Instantiates a new PBRSpecularGlossinessMaterial instance.
*
* @param name The material name
* @param scene The scene the material will be use in.
*/
function PBRSpecularGlossinessMaterial(name, scene) {
var _this = _super.call(this, name, scene) || this;
_this._useMicroSurfaceFromReflectivityMapAlpha = true;
return _this;
}
/**
* Return the currrent class name of the material.
*/
PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
return "PBRSpecularGlossinessMaterial";
};
/**
* Makes a duplicate of the current material.
* @param name - name to use for the new material.
*/
PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
var _this = this;
var clone = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
clone.id = name;
clone.name = name;
this.clearCoat.copyTo(clone.clearCoat);
this.anisotropy.copyTo(clone.anisotropy);
this.brdf.copyTo(clone.brdf);
this.sheen.copyTo(clone.sheen);
this.subSurface.copyTo(clone.subSurface);
return clone;
};
/**
* Serialize the material to a parsable JSON object.
*/
PBRSpecularGlossinessMaterial.prototype.serialize = function () {
var serializationObject = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
serializationObject.clearCoat = this.clearCoat.serialize();
serializationObject.anisotropy = this.anisotropy.serialize();
serializationObject.brdf = this.brdf.serialize();
serializationObject.sheen = this.sheen.serialize();
serializationObject.subSurface = this.subSurface.serialize();
return serializationObject;
};
/**
* Parses a JSON object correponding to the serialize function.
*/
PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
var material = _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
if (source.clearCoat) {
material.clearCoat.parse(source.clearCoat, scene, rootUrl);
}
if (source.anisotropy) {
material.anisotropy.parse(source.anisotropy, scene, rootUrl);
}
if (source.brdf) {
material.brdf.parse(source.brdf, scene, rootUrl);
}
if (source.sheen) {
material.sheen.parse(source.sheen, scene, rootUrl);
}
if (source.subSurface) {
material.subSurface.parse(source.subSurface, scene, rootUrl);
}
return material;
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("diffuse"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])("specular"),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_microSurface")
], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
return PBRSpecularGlossinessMaterial;
}(_pbrBaseSimpleMaterial__WEBPACK_IMPORTED_MODULE_2__["PBRBaseSimpleMaterial"]));
_Misc_typeStore__WEBPACK_IMPORTED_MODULE_3__["_TypeStore"].RegisteredTypes["BABYLON.PBRSpecularGlossinessMaterial"] = PBRSpecularGlossinessMaterial;
/***/ }),
/***/ "./Materials/PBR/pbrSubSurfaceConfiguration.ts":
/*!*****************************************************!*\
!*** ./Materials/PBR/pbrSubSurfaceConfiguration.ts ***!
\*****************************************************/
/*! exports provided: PBRSubSurfaceConfiguration */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PBRSubSurfaceConfiguration", function() { return PBRSubSurfaceConfiguration; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../Misc/decorators */ "./Misc/decorators.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _materialFlags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../materialFlags */ "./Materials/materialFlags.ts");
/* harmony import */ var _Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../Materials/materialHelper */ "./Materials/materialHelper.ts");
/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../Maths/math.scalar */ "./Maths/math.scalar.ts");
/**
* Define the code related to the sub surface parameters of the pbr material.
*/
var PBRSubSurfaceConfiguration = /** @class */ (function () {
/**
* Instantiate a new istance of sub surface configuration.
* @param markAllSubMeshesAsTexturesDirty Callback to flag the material to dirty
* @param markScenePrePassDirty Callback to flag the scene as prepass dirty
* @param scene The scene
*/
function PBRSubSurfaceConfiguration(markAllSubMeshesAsTexturesDirty, markScenePrePassDirty, scene) {
this._isRefractionEnabled = false;
/**
* Defines if the refraction is enabled in the material.
*/
this.isRefractionEnabled = false;
this._isTranslucencyEnabled = false;
/**
* Defines if the translucency is enabled in the material.
*/
this.isTranslucencyEnabled = false;
this._isScatteringEnabled = false;
/**
* Defines if the sub surface scattering is enabled in the material.
*/
this.isScatteringEnabled = false;
this._scatteringDiffusionProfileIndex = 0;
/**
* Defines the refraction intensity of the material.
* The refraction when enabled replaces the Diffuse part of the material.
* The intensity helps transitionning between diffuse and refraction.
*/
this.refractionIntensity = 1;
/**
* Defines the translucency intensity of the material.
* When translucency has been enabled, this defines how much of the "translucency"
* is addded to the diffuse part of the material.
*/
this.translucencyIntensity = 1;
/**
* When enabled, transparent surfaces will be tinted with the albedo colour (independent of thickness)
*/
this.useAlbedoToTintRefraction = false;
this._thicknessTexture = null;
/**
* Stores the average thickness of a mesh in a texture (The texture is holding the values linearly).
* The red channel of the texture should contain the thickness remapped between 0 and 1.
* 0 would mean minimumThickness
* 1 would mean maximumThickness
* The other channels might be use as a mask to vary the different effects intensity.
*/
this.thicknessTexture = null;
this._refractionTexture = null;
/**
* Defines the texture to use for refraction.
*/
this.refractionTexture = null;
this._indexOfRefraction = 1.5;
/**
* Index of refraction of the material base layer.
* https://en.wikipedia.org/wiki/List_of_refractive_indices
*
* This does not only impact refraction but also the Base F0 of Dielectric Materials.
*
* From dielectric fresnel rules: F0 = square((iorT - iorI) / (iorT + iorI))
*/
this.indexOfRefraction = 1.5;
this._volumeIndexOfRefraction = -1.0;
this._invertRefractionY = false;
/**
* Controls if refraction needs to be inverted on Y. This could be useful for procedural texture.
*/
this.invertRefractionY = false;
this._linkRefractionWithTransparency = false;
/**
* This parameters will make the material used its opacity to control how much it is refracting aginst not.
* Materials half opaque for instance using refraction could benefit from this control.
*/
this.linkRefractionWithTransparency = false;
/**
* Defines the minimum thickness stored in the thickness map.
* If no thickness map is defined, this value will be used to simulate thickness.
*/
this.minimumThickness = 0;
/**
* Defines the maximum thickness stored in the thickness map.
*/
this.maximumThickness = 1;
/**
* Defines the volume tint of the material.
* This is used for both translucency and scattering.
*/
this.tintColor = _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"].White();
/**
* Defines the distance at which the tint color should be found in the media.
* This is used for refraction only.
*/
this.tintColorAtDistance = 1;
/**
* Defines how far each channel transmit through the media.
* It is defined as a color to simplify it selection.
*/
this.diffusionDistance = _Maths_math_color__WEBPACK_IMPORTED_MODULE_2__["Color3"].White();
this._useMaskFromThicknessTexture = false;
/**
* Stores the intensity of the different subsurface effects in the thickness texture.
* * the green channel is the translucency intensity.
* * the blue channel is the scattering intensity.
* * the alpha channel is the refraction intensity.
*/
this.useMaskFromThicknessTexture = false;
this._internalMarkAllSubMeshesAsTexturesDirty = markAllSubMeshesAsTexturesDirty;
this._internalMarkScenePrePassDirty = markScenePrePassDirty;
this._scene = scene;
}
Object.defineProperty(PBRSubSurfaceConfiguration.prototype, "scatteringDiffusionProfile", {
/**
* Diffusion profile for subsurface scattering.
* Useful for better scattering in the skins or foliages.
*/
get: function () {
if (!this._scene.prePassRenderer) {
return null;
}
return this._scene.prePassRenderer.subSurfaceConfiguration.ssDiffusionProfileColors[this._scatteringDiffusionProfileIndex];
},
set: function (c) {
if (!this._scene.enablePrePassRenderer()) {
// Not supported
return;
}
// addDiffusionProfile automatically checks for doubles
if (c) {
this._scatteringDiffusionProfileIndex = this._scene.prePassRenderer.subSurfaceConfiguration.addDiffusionProfile(c);
}
},
enumerable: false,
configurable: true
});
Object.defineProperty(PBRSubSurfaceConfiguration.prototype, "volumeIndexOfRefraction", {
/**
* Index of refraction of the material's volume.
* https://en.wikipedia.org/wiki/List_of_refractive_indices
*
* This ONLY impacts refraction. If not provided or given a non-valid value,
* the volume will use the same IOR as the surface.
*/
get: function () {
if (this._volumeIndexOfRefraction >= 1.0) {
return this._volumeIndexOfRefraction;
}
return this._indexOfRefraction;
},
set: function (value) {
if (value >= 1.0) {
this._volumeIndexOfRefraction = value;
}
else {
this._volumeIndexOfRefraction = -1.0;
}
},
enumerable: false,
configurable: true
});
/** @hidden */
PBRSubSurfaceConfiguration.prototype._markAllSubMeshesAsTexturesDirty = function () {
this._internalMarkAllSubMeshesAsTexturesDirty();
};
/** @hidden */
PBRSubSurfaceConfiguration.prototype._markScenePrePassDirty = function () {
this._internalMarkScenePrePassDirty();
};
/**
* Gets wehter the submesh is ready to be used or not.
* @param defines the list of "defines" to update.
* @param scene defines the scene the material belongs to.
* @returns - boolean indicating that the submesh is ready or not.
*/
PBRSubSurfaceConfiguration.prototype.isReadyForSubMesh = function (defines, scene) {
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) {
if (!this._thicknessTexture.isReadyOrNotBlocking()) {
return false;
}
}
var refractionTexture = this._getRefractionTexture(scene);
if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) {
if (!refractionTexture.isReadyOrNotBlocking()) {
return false;
}
}
}
}
return true;
};
/**
* Checks to see if a texture is used in the material.
* @param defines the list of "defines" to update.
* @param scene defines the scene to the material belongs to.
*/
PBRSubSurfaceConfiguration.prototype.prepareDefines = function (defines, scene) {
if (defines._areTexturesDirty) {
defines.SUBSURFACE = false;
defines.SS_TRANSLUCENCY = this._isTranslucencyEnabled;
defines.SS_SCATTERING = this._isScatteringEnabled;
defines.SS_THICKNESSANDMASK_TEXTURE = false;
defines.SS_MASK_FROM_THICKNESS_TEXTURE = false;
defines.SS_REFRACTION = false;
defines.SS_REFRACTIONMAP_3D = false;
defines.SS_GAMMAREFRACTION = false;
defines.SS_RGBDREFRACTION = false;
defines.SS_LINEARSPECULARREFRACTION = false;
defines.SS_REFRACTIONMAP_OPPOSITEZ = false;
defines.SS_LODINREFRACTIONALPHA = false;
defines.SS_LINKREFRACTIONTOTRANSPARENCY = false;
defines.SS_ALBEDOFORREFRACTIONTINT = false;
if (this._isRefractionEnabled || this._isTranslucencyEnabled || this._isScatteringEnabled) {
defines.SUBSURFACE = true;
if (defines._areTexturesDirty) {
if (scene.texturesEnabled) {
if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) {
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].PrepareDefinesForMergedUV(this._thicknessTexture, defines, "SS_THICKNESSANDMASK_TEXTURE");
}
}
}
defines.SS_MASK_FROM_THICKNESS_TEXTURE = this._useMaskFromThicknessTexture;
}
if (this._isRefractionEnabled) {
if (scene.texturesEnabled) {
var refractionTexture = this._getRefractionTexture(scene);
if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) {
defines.SS_REFRACTION = true;
defines.SS_REFRACTIONMAP_3D = refractionTexture.isCube;
defines.SS_GAMMAREFRACTION = refractionTexture.gammaSpace;
defines.SS_RGBDREFRACTION = refractionTexture.isRGBD;
defines.SS_LINEARSPECULARREFRACTION = refractionTexture.linearSpecularLOD;
defines.SS_REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
defines.SS_LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
defines.SS_LINKREFRACTIONTOTRANSPARENCY = this._linkRefractionWithTransparency;
defines.SS_ALBEDOFORREFRACTIONTINT = this.useAlbedoToTintRefraction;
}
}
}
}
};
/**
* Binds the material data.
* @param uniformBuffer defines the Uniform buffer to fill in.
* @param scene defines the scene the material belongs to.
* @param engine defines the engine the material belongs to.
* @param isFrozen defines whether the material is frozen or not.
* @param lodBasedMicrosurface defines whether the material relies on lod based microsurface or not.
* @param realTimeFiltering defines whether the textures should be filtered on the fly.
*/
PBRSubSurfaceConfiguration.prototype.bindForSubMesh = function (uniformBuffer, scene, engine, isFrozen, lodBasedMicrosurface, realTimeFiltering) {
var refractionTexture = this._getRefractionTexture(scene);
if (!uniformBuffer.useUbo || !isFrozen || !uniformBuffer.isSync) {
if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) {
uniformBuffer.updateFloat2("vThicknessInfos", this._thicknessTexture.coordinatesIndex, this._thicknessTexture.level);
_Materials_materialHelper__WEBPACK_IMPORTED_MODULE_4__["MaterialHelper"].BindTextureMatrix(this._thicknessTexture, uniformBuffer, "thickness");
}
uniformBuffer.updateFloat2("vThicknessParam", this.minimumThickness, this.maximumThickness - this.minimumThickness);
if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) {
uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
var depth = 1.0;
if (!refractionTexture.isCube) {
if (refractionTexture.depth) {
depth = refractionTexture.depth;
}
}
var width = refractionTexture.getSize().width;
var refractionIor = this.volumeIndexOfRefraction;
uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, 1 / refractionIor, depth, this._invertRefractionY ? -1 : 1);
uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
if (realTimeFiltering) {
uniformBuffer.updateFloat2("vRefractionFilteringInfo", width, _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_5__["Scalar"].Log2(width));
}
}
if (this.isScatteringEnabled) {
uniformBuffer.updateFloat("scatteringDiffusionProfile", this._scatteringDiffusionProfileIndex);
}
uniformBuffer.updateColor3("vDiffusionDistance", this.diffusionDistance);
uniformBuffer.updateFloat4("vTintColor", this.tintColor.r, this.tintColor.g, this.tintColor.b, this.tintColorAtDistance);
uniformBuffer.updateFloat3("vSubSurfaceIntensity", this.refractionIntensity, this.translucencyIntensity, 0);
}
// Textures
if (scene.texturesEnabled) {
if (this._thicknessTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].ThicknessTextureEnabled) {
uniformBuffer.setTexture("thicknessSampler", this._thicknessTexture);
}
if (refractionTexture && _materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled) {
if (lodBasedMicrosurface) {
uniformBuffer.setTexture("refractionSampler", refractionTexture);
}
else {
uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
}
}
}
};
/**
* Unbinds the material from the mesh.
* @param activeEffect defines the effect that should be unbound from.
* @returns true if unbound, otherwise false
*/
PBRSubSurfaceConfiguration.prototype.unbind = function (activeEffect) {
if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
activeEffect.setTexture("refractionSampler", null);
return true;
}
return false;
};
/**
* Returns the texture used for refraction or null if none is used.
* @param scene defines the scene the material belongs to.
* @returns - Refraction texture if present. If no refraction texture and refraction
* is linked with transparency, returns environment texture. Otherwise, returns null.
*/
PBRSubSurfaceConfiguration.prototype._getRefractionTexture = function (scene) {
if (this._refractionTexture) {
return this._refractionTexture;
}
if (this._isRefractionEnabled) {
return scene.environmentTexture;
}
return null;
};
Object.defineProperty(PBRSubSurfaceConfiguration.prototype, "disableAlphaBlending", {
/**
* Returns true if alpha blending should be disabled.
*/
get: function () {
return this.isRefractionEnabled && this._linkRefractionWithTransparency;
},
enumerable: false,
configurable: true
});
/**
* Fills the list of render target textures.
* @param renderTargets the list of render targets to update
*/
PBRSubSurfaceConfiguration.prototype.fillRenderTargetTextures = function (renderTargets) {
if (_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
renderTargets.push(this._refractionTexture);
}
};
/**
* Checks to see if a texture is used in the material.
* @param texture - Base texture to use.
* @returns - Boolean specifying if a texture is used in the material.
*/
PBRSubSurfaceConfiguration.prototype.hasTexture = function (texture) {
if (this._thicknessTexture === texture) {
return true;
}
if (this._refractionTexture === texture) {
return true;
}
return false;
};
/**
* Gets a boolean indicating that current material needs to register RTT
* @returns true if this uses a render target otherwise false.
*/
PBRSubSurfaceConfiguration.prototype.hasRenderTargetTextures = function () {
if (_materialFlags__WEBPACK_IMPORTED_MODULE_3__["MaterialFlags"].RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
return true;
}
return false;
};
/**
* Returns an array of the actively used textures.
* @param activeTextures Array of BaseTextures
*/
PBRSubSurfaceConfiguration.prototype.getActiveTextures = function (activeTextures) {
if (this._thicknessTexture) {
activeTextures.push(this._thicknessTexture);
}
if (this._refractionTexture) {
activeTextures.push(this._refractionTexture);
}
};
/**
* Returns the animatable textures.
* @param animatables Array of animatable textures.
*/
PBRSubSurfaceConfiguration.prototype.getAnimatables = function (animatables) {
if (this._thicknessTexture && this._thicknessTexture.animations && this._thicknessTexture.animations.length > 0) {
animatables.push(this._thicknessTexture);
}
if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
animatables.push(this._refractionTexture);
}
};
/**
* Disposes the resources of the material.
* @param forceDisposeTextures - Forces the disposal of all textures.
*/
PBRSubSurfaceConfiguration.prototype.dispose = function (forceDisposeTextures) {
if (forceDisposeTextures) {
if (this._thicknessTexture) {
this._thicknessTexture.dispose();
}
if (this._refractionTexture) {
this._refractionTexture.dispose();
}
}
};
/**
* Get the current class name of the texture useful for serialization or dynamic coding.
* @returns "PBRSubSurfaceConfiguration"
*/
PBRSubSurfaceConfiguration.prototype.getClassName = function () {
return "PBRSubSurfaceConfiguration";
};
/**
* Add fallbacks to the effect fallbacks list.
* @param defines defines the Base texture to use.
* @param fallbacks defines the current fallback list.
* @param currentRank defines the current fallback rank.
* @returns the new fallback rank.
*/
PBRSubSurfaceConfiguration.AddFallbacks = function (defines, fallbacks, currentRank) {
if (defines.SS_SCATTERING) {
fallbacks.addFallback(currentRank++, "SS_SCATTERING");
}
if (defines.SS_TRANSLUCENCY) {
fallbacks.addFallback(currentRank++, "SS_TRANSLUCENCY");
}
return currentRank;
};
/**
* Add the required uniforms to the current list.
* @param uniforms defines the current uniform list.
*/
PBRSubSurfaceConfiguration.AddUniforms = function (uniforms) {
uniforms.push("vDiffusionDistance", "vTintColor", "vSubSurfaceIntensity", "vRefractionMicrosurfaceInfos", "vRefractionFilteringInfo", "vRefractionInfos", "vThicknessInfos", "vThicknessParam", "refractionMatrix", "thicknessMatrix", "scatteringDiffusionProfile");
};
/**
* Add the required samplers to the current list.
* @param samplers defines the current sampler list.
*/
PBRSubSurfaceConfiguration.AddSamplers = function (samplers) {
samplers.push("thicknessSampler", "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh");
};
/**
* Add the required uniforms to the current buffer.
* @param uniformBuffer defines the current uniform buffer.
*/
PBRSubSurfaceConfiguration.PrepareUniformBuffer = function (uniformBuffer) {
uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
uniformBuffer.addUniform("vRefractionFilteringInfo", 2);
uniformBuffer.addUniform("vRefractionInfos", 4);
uniformBuffer.addUniform("refractionMatrix", 16);
uniformBuffer.addUniform("vThicknessInfos", 2);
uniformBuffer.addUniform("thicknessMatrix", 16);
uniformBuffer.addUniform("vThicknessParam", 2);
uniformBuffer.addUniform("vDiffusionDistance", 3);
uniformBuffer.addUniform("vTintColor", 4);
uniformBuffer.addUniform("vSubSurfaceIntensity", 3);
uniformBuffer.addUniform("scatteringDiffusionProfile", 1);
};
/**
* Makes a duplicate of the current configuration into another one.
* @param configuration define the config where to copy the info
*/
PBRSubSurfaceConfiguration.prototype.copyTo = function (configuration) {
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Clone(function () { return configuration; }, this);
};
/**
* Serializes this Sub Surface configuration.
* @returns - An object with the serialized config.
*/
PBRSubSurfaceConfiguration.prototype.serialize = function () {
return _Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Serialize(this);
};
/**
* Parses a anisotropy Configuration from a serialized object.
* @param source - Serialized object.
* @param scene Defines the scene we are parsing for
* @param rootUrl Defines the rootUrl to load from
*/
PBRSubSurfaceConfiguration.prototype.parse = function (source, scene, rootUrl) {
var _this = this;
_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["SerializationHelper"].Parse(function () { return _this; }, source, scene, rootUrl);
};
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "isRefractionEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "isTranslucencyEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markScenePrePassDirty")
], PBRSubSurfaceConfiguration.prototype, "isScatteringEnabled", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "_scatteringDiffusionProfileIndex", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "refractionIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "translucencyIntensity", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "useAlbedoToTintRefraction", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "thicknessTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsTexture"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "refractionTexture", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "indexOfRefraction", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "volumeIndexOfRefraction", null);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "invertRefractionY", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "linkRefractionWithTransparency", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "minimumThickness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "maximumThickness", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], PBRSubSurfaceConfiguration.prototype, "tintColor", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])()
], PBRSubSurfaceConfiguration.prototype, "tintColorAtDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serializeAsColor3"])()
], PBRSubSurfaceConfiguration.prototype, "diffusionDistance", void 0);
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"])([
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["serialize"])(),
Object(_Misc_decorators__WEBPACK_IMPORTED_MODULE_1__["expandToProperty"])("_markAllSubMeshesAsTexturesDirty")
], PBRSubSurfaceConfiguration.prototype, "useMaskFromThicknessTexture", void 0);
return PBRSubSurfaceConfiguration;
}());
/***/ }),
/***/ "./Materials/Textures/Filtering/hdrFiltering.ts":
/*!******************************************************!*\
!*** ./Materials/Textures/Filtering/hdrFiltering.ts ***!
\******************************************************/
/*! exports provided: HDRFiltering */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HDRFiltering", function() { return HDRFiltering; });
/* harmony import */ var _Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Maths/math */ "./Maths/math.ts");
/* harmony import */ var _Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Maths/math.scalar */ "./Maths/math.scalar.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Engines/constants */ "./Engines/constants.ts");
/* harmony import */ var _Materials_effectRenderer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Materials/effectRenderer */ "./Materials/effectRenderer.ts");
/* harmony import */ var _Shaders_hdrFiltering_vertex__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Shaders/hdrFiltering.vertex */ "./Shaders/hdrFiltering.vertex.ts");
/* harmony import */ var _Shaders_hdrFiltering_fragment__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Shaders/hdrFiltering.fragment */ "./Shaders/hdrFiltering.fragment.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ../../../Misc/logger */ "./Misc/logger.ts");
/**
* Filters HDR maps to get correct renderings of PBR reflections
*/
var HDRFiltering = /** @class */ (function () {
/**
* Instantiates HDR filter for reflection maps
*
* @param engine Thin engine
* @param options Options
*/
function HDRFiltering(engine, options) {
if (options === void 0) { options = {}; }
this._lodGenerationOffset = 0;
this._lodGenerationScale = 0.8;
/**
* Quality switch for prefiltering. Should be set to `Constants.TEXTURE_FILTERING_QUALITY_OFFLINE` unless
* you care about baking speed.
*/
this.quality = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_FILTERING_QUALITY_OFFLINE;
/**
* Scales pixel intensity for the input HDR map.
*/
this.hdrScale = 1;
// pass
this._engine = engine;
this.hdrScale = options.hdrScale || this.hdrScale;
this.quality = options.hdrScale || this.quality;
}
HDRFiltering.prototype._createRenderTarget = function (size) {
var textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_UNSIGNED_BYTE;
if (this._engine.getCaps().textureHalfFloatRender) {
textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_HALF_FLOAT;
}
else if (this._engine.getCaps().textureFloatRender) {
textureType = _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURETYPE_FLOAT;
}
var texture = this._engine.createRenderTargetCubeTexture(size, {
format: _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTUREFORMAT_RGBA,
type: textureType,
generateMipMaps: false,
generateDepthBuffer: false,
generateStencilBuffer: false,
samplingMode: _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_NEAREST_SAMPLINGMODE
});
this._engine.updateTextureWrappingMode(texture, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_CLAMP_ADDRESSMODE, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_CLAMP_ADDRESSMODE, _Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_CLAMP_ADDRESSMODE);
this._engine.updateTextureSamplingMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE, texture, true);
return texture;
};
HDRFiltering.prototype._prefilterInternal = function (texture) {
var width = texture.getSize().width;
var mipmapsCount = Math.round(_Maths_math_scalar__WEBPACK_IMPORTED_MODULE_1__["Scalar"].Log2(width)) + 1;
var effect = this._effectWrapper.effect;
var outputTexture = this._createRenderTarget(width);
this._effectRenderer.setViewport();
var intTexture = texture.getInternalTexture();
if (intTexture) {
// Just in case generate fresh clean mips.
this._engine.updateTextureSamplingMode(_Engines_constants__WEBPACK_IMPORTED_MODULE_2__["Constants"].TEXTURE_TRILINEAR_SAMPLINGMODE, intTexture, true);
}
this._effectRenderer.applyEffectWrapper(this._effectWrapper);
var directions = [
[new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, -1), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, -1, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, 0, 0)],
[new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 1), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, -1, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](-1, 0, 0)],
[new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 1), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 1, 0)],
[new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, -1), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, -1, 0)],
[new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](1, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, -1, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, 1)],
[new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](-1, 0, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, -1, 0), new _Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](0, 0, -1)],
];
effect.setFloat("hdrScale", this.hdrScale);
effect.setFloat2("vFilteringInfo", texture.getSize().width, mipmapsCount);
effect.setTexture("inputTexture", texture);
for (var face = 0; face < 6; face++) {
effect.setVector3("up", directions[face][0]);
effect.setVector3("right", directions[face][1]);
effect.setVector3("front", directions[face][2]);
for (var lod = 0; lod < mipmapsCount; lod++) {
this._engine.bindFramebuffer(outputTexture, face, undefined, undefined, true, lod);
this._effectRenderer.applyEffectWrapper(this._effectWrapper);
var alpha = Math.pow(2, (lod - this._lodGenerationOffset) / this._lodGenerationScale) / width;
if (lod === 0) {
alpha = 0;
}
effect.setFloat("alphaG", alpha);
this._effectRenderer.draw();
}
}
// Cleanup
this._effectRenderer.restoreStates();
this._engine.restoreDefaultFramebuffer();
this._engine._releaseFramebufferObjects(outputTexture);
this._engine._releaseTexture(texture._texture);
// Internal Swap
outputTexture._swapAndDie(texture._texture);
texture._prefiltered = true;
return texture;
};
HDRFiltering.prototype._createEffect = function (texture, onCompiled) {
var defines = [];
if (texture.gammaSpace) {
defines.push("#define GAMMA_INPUT");
}
defines.push("#define NUM_SAMPLES " + this.quality + "u"); // unsigned int
var effectWrapper = new _Materials_effectRenderer__WEBPACK_IMPORTED_MODULE_3__["EffectWrapper"]({
engine: this._engine,
name: "hdrFiltering",
vertexShader: "hdrFiltering",
fragmentShader: "hdrFiltering",
samplerNames: ["inputTexture"],
uniformNames: ["vSampleDirections", "vWeights", "up", "right", "front", "vFilteringInfo", "hdrScale", "alphaG"],
useShaderStore: true,
defines: defines,
onCompiled: onCompiled
});
return effectWrapper;
};
/**
* Get a value indicating if the filter is ready to be used
* @param texture Texture to filter
* @returns true if the filter is ready
*/
HDRFiltering.prototype.isReady = function (texture) {
return (texture.isReady() && this._effectWrapper.effect.isReady());
};
/**
* Prefilters a cube texture to have mipmap levels representing roughness values.
* Prefiltering will be invoked at the end of next rendering pass.
* This has to be done once the map is loaded, and has not been prefiltered by a third party software.
* See http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf for more information
* @param texture Texture to filter
* @param onFinished Callback when filtering is done
* @return Promise called when prefiltering is done
*/
HDRFiltering.prototype.prefilter = function (texture, onFinished) {
var _this = this;
if (onFinished === void 0) { onFinished = null; }
if (this._engine.webGLVersion === 1) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_6__["Logger"].Warn("HDR prefiltering is not available in WebGL 1., you can use real time filtering instead.");
return;
}
return new Promise(function (resolve) {
_this._effectRenderer = new _Materials_effectRenderer__WEBPACK_IMPORTED_MODULE_3__["EffectRenderer"](_this._engine);
_this._effectWrapper = _this._createEffect(texture);
_this._effectWrapper.effect.executeWhenCompiled(function () {
_this._prefilterInternal(texture);
_this._effectRenderer.dispose();
_this._effectWrapper.dispose();
resolve();
if (onFinished) {
onFinished();
}
});
});
};
return HDRFiltering;
}());
/***/ }),
/***/ "./Materials/Textures/Loaders/basisTextureLoader.ts":
/*!**********************************************************!*\
!*** ./Materials/Textures/Loaders/basisTextureLoader.ts ***!
\**********************************************************/
/*! exports provided: _BasisTextureLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_BasisTextureLoader", function() { return _BasisTextureLoader; });
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Misc_basis__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Misc/basis */ "./Misc/basis.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/tools */ "./Misc/tools.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Misc/stringTools */ "./Misc/stringTools.ts");
/**
* Loader for .basis file format
*/
var _BasisTextureLoader = /** @class */ (function () {
function _BasisTextureLoader() {
/**
* Defines whether the loader supports cascade loading the different faces.
*/
this.supportCascades = false;
}
/**
* This returns if the loader support the current file information.
* @param extension defines the file extension of the file being loaded
* @returns true if the loader can load the specified file
*/
_BasisTextureLoader.prototype.canLoad = function (extension) {
return _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__["StringTools"].EndsWith(extension, ".basis");
};
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
_BasisTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data)) {
return;
}
var caps = texture.getEngine().getCaps();
var transcodeConfig = {
supportedCompressionFormats: {
etc1: caps.etc1 ? true : false,
s3tc: caps.s3tc ? true : false,
pvrtc: caps.pvrtc ? true : false,
etc2: caps.etc2 ? true : false
}
};
_Misc_basis__WEBPACK_IMPORTED_MODULE_1__["BasisTools"].TranscodeAsync(data, transcodeConfig).then(function (result) {
var hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;
_Misc_basis__WEBPACK_IMPORTED_MODULE_1__["BasisTools"].LoadTextureFromTranscodeResult(texture, result);
texture.getEngine()._setCubeMapTextureParams(hasMipmap);
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
}).catch(function (err) {
_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Warn("Failed to transcode Basis file, transcoding may not be supported on this device");
texture.isReady = true;
});
};
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
_BasisTextureLoader.prototype.loadData = function (data, texture, callback) {
var caps = texture.getEngine().getCaps();
var transcodeConfig = {
supportedCompressionFormats: {
etc1: caps.etc1 ? true : false,
s3tc: caps.s3tc ? true : false,
pvrtc: caps.pvrtc ? true : false,
etc2: caps.etc2 ? true : false
}
};
_Misc_basis__WEBPACK_IMPORTED_MODULE_1__["BasisTools"].TranscodeAsync(data, transcodeConfig).then(function (result) {
var rootImage = result.fileInfo.images[0].levels[0];
var hasMipmap = result.fileInfo.images[0].levels.length > 1 && texture.generateMipMaps;
callback(rootImage.width, rootImage.height, hasMipmap, result.format !== -1, function () {
_Misc_basis__WEBPACK_IMPORTED_MODULE_1__["BasisTools"].LoadTextureFromTranscodeResult(texture, result);
});
}).catch(function (err) {
_Misc_tools__WEBPACK_IMPORTED_MODULE_2__["Tools"].Warn("Failed to transcode Basis file, transcoding may not be supported on this device");
callback(0, 0, false, false, function () {
});
});
};
return _BasisTextureLoader;
}());
// Register the loader.
_Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"]._TextureLoaders.push(new _BasisTextureLoader());
/***/ }),
/***/ "./Materials/Textures/Loaders/ddsTextureLoader.ts":
/*!********************************************************!*\
!*** ./Materials/Textures/Loaders/ddsTextureLoader.ts ***!
\********************************************************/
/*! exports provided: _DDSTextureLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _DDSTextureLoader; });
/* harmony import */ var _Maths_sphericalPolynomial__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Maths/sphericalPolynomial */ "./Maths/sphericalPolynomial.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Misc_dds__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/dds */ "./Misc/dds.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Misc/stringTools */ "./Misc/stringTools.ts");
/**
* Implementation of the DDS Texture Loader.
* @hidden
*/
var _DDSTextureLoader = /** @class */ (function () {
function _DDSTextureLoader() {
/**
* Defines wether the loader supports cascade loading the different faces.
*/
this.supportCascades = true;
}
/**
* This returns if the loader support the current file information.
* @param extension defines the file extension of the file being loaded
* @returns true if the loader can load the specified file
*/
_DDSTextureLoader.prototype.canLoad = function (extension) {
return _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__["StringTools"].EndsWith(extension, ".dds");
};
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
_DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
var engine = texture.getEngine();
var info;
var loadMipmap = false;
if (Array.isArray(imgs)) {
for (var index = 0; index < imgs.length; index++) {
var data_1 = imgs[index];
info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data_1);
texture.width = info.width;
texture.height = info.height;
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
engine._unpackFlipY(info.isCompressed);
_Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
if (!info.isFourCC && info.mipmapCount === 1) {
engine.generateMipMapsForCubemap(texture);
}
}
}
else {
var data = imgs;
info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data);
texture.width = info.width;
texture.height = info.height;
if (createPolynomials) {
info.sphericalPolynomial = new _Maths_sphericalPolynomial__WEBPACK_IMPORTED_MODULE_0__["SphericalPolynomial"]();
}
loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
engine._unpackFlipY(info.isCompressed);
_Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
if (!info.isFourCC && info.mipmapCount === 1) {
// Do not unbind as we still need to set the parameters.
engine.generateMipMapsForCubemap(texture, false);
}
}
engine._setCubeMapTextureParams(loadMipmap);
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
}
};
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
_DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
var info = _Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].GetDDSInfo(data);
var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
_Misc_dds__WEBPACK_IMPORTED_MODULE_2__["DDSTools"].UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
});
};
return _DDSTextureLoader;
}());
// Register the loader.
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _DDSTextureLoader());
/***/ }),
/***/ "./Materials/Textures/Loaders/envTextureLoader.ts":
/*!********************************************************!*\
!*** ./Materials/Textures/Loaders/envTextureLoader.ts ***!
\********************************************************/
/*! exports provided: _ENVTextureLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _ENVTextureLoader; });
/* harmony import */ var _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/environmentTextureTools */ "./Misc/environmentTextureTools.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/stringTools */ "./Misc/stringTools.ts");
/**
* Implementation of the ENV Texture Loader.
* @hidden
*/
var _ENVTextureLoader = /** @class */ (function () {
function _ENVTextureLoader() {
/**
* Defines wether the loader supports cascade loading the different faces.
*/
this.supportCascades = false;
}
/**
* This returns if the loader support the current file information.
* @param extension defines the file extension of the file being loaded
* @returns true if the loader can load the specified file
*/
_ENVTextureLoader.prototype.canLoad = function (extension) {
return _Misc_stringTools__WEBPACK_IMPORTED_MODULE_2__["StringTools"].EndsWith(extension, ".env");
};
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
_ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data)) {
return;
}
var info = _Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].GetEnvInfo(data);
if (info) {
texture.width = info.width;
texture.height = info.width;
_Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].UploadEnvSpherical(texture, info);
_Misc_environmentTextureTools__WEBPACK_IMPORTED_MODULE_0__["EnvironmentTextureTools"].UploadEnvLevelsAsync(texture, data, info).then(function () {
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
});
}
else if (onError) {
onError("Can not parse the environment file", null);
}
};
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
_ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
throw ".env not supported in 2d.";
};
return _ENVTextureLoader;
}());
// Register the loader.
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _ENVTextureLoader());
/***/ }),
/***/ "./Materials/Textures/Loaders/index.ts":
/*!*********************************************!*\
!*** ./Materials/Textures/Loaders/index.ts ***!
\*********************************************/
/*! exports provided: _DDSTextureLoader, _ENVTextureLoader, _KTXTextureLoader, _TGATextureLoader, _BasisTextureLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _ddsTextureLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./ddsTextureLoader */ "./Materials/Textures/Loaders/ddsTextureLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_DDSTextureLoader", function() { return _ddsTextureLoader__WEBPACK_IMPORTED_MODULE_0__["_DDSTextureLoader"]; });
/* harmony import */ var _envTextureLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./envTextureLoader */ "./Materials/Textures/Loaders/envTextureLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_ENVTextureLoader", function() { return _envTextureLoader__WEBPACK_IMPORTED_MODULE_1__["_ENVTextureLoader"]; });
/* harmony import */ var _ktxTextureLoader__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./ktxTextureLoader */ "./Materials/Textures/Loaders/ktxTextureLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _ktxTextureLoader__WEBPACK_IMPORTED_MODULE_2__["_KTXTextureLoader"]; });
/* harmony import */ var _tgaTextureLoader__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./tgaTextureLoader */ "./Materials/Textures/Loaders/tgaTextureLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _tgaTextureLoader__WEBPACK_IMPORTED_MODULE_3__["_TGATextureLoader"]; });
/* harmony import */ var _basisTextureLoader__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./basisTextureLoader */ "./Materials/Textures/Loaders/basisTextureLoader.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BasisTextureLoader", function() { return _basisTextureLoader__WEBPACK_IMPORTED_MODULE_4__["_BasisTextureLoader"]; });
/***/ }),
/***/ "./Materials/Textures/Loaders/ktxTextureLoader.ts":
/*!********************************************************!*\
!*** ./Materials/Textures/Loaders/ktxTextureLoader.ts ***!
\********************************************************/
/*! exports provided: _KTXTextureLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_KTXTextureLoader", function() { return _KTXTextureLoader; });
/* harmony import */ var _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/khronosTextureContainer */ "./Misc/khronosTextureContainer.ts");
/* harmony import */ var _Misc_khronosTextureContainer2__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Misc/khronosTextureContainer2 */ "./Misc/khronosTextureContainer2.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../Misc/stringTools */ "./Misc/stringTools.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Misc/logger */ "./Misc/logger.ts");
/**
* Implementation of the KTX Texture Loader.
* @hidden
*/
var _KTXTextureLoader = /** @class */ (function () {
function _KTXTextureLoader() {
/**
* Defines wether the loader supports cascade loading the different faces.
*/
this.supportCascades = false;
}
/**
* This returns if the loader support the current file information.
* @param extension defines the file extension of the file being loaded
* @param mimeType defines the optional mime type of the file being loaded
* @returns true if the loader can load the specified file
*/
_KTXTextureLoader.prototype.canLoad = function (extension, mimeType) {
// The ".ktx2" file extension is still up for debate: https://github.com/KhronosGroup/KTX-Specification/issues/18
return _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__["StringTools"].EndsWith(extension, ".ktx") || _Misc_stringTools__WEBPACK_IMPORTED_MODULE_3__["StringTools"].EndsWith(extension, ".ktx2") || mimeType === "image/ktx" || mimeType === "image/ktx2";
};
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
_KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
if (Array.isArray(data)) {
return;
}
// Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture
texture._invertVScale = !texture.invertY;
var engine = texture.getEngine();
var ktx = new _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"](data, 6);
var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
engine._unpackFlipY(true);
ktx.uploadLevels(texture, texture.generateMipMaps);
texture.width = ktx.pixelWidth;
texture.height = ktx.pixelHeight;
engine._setCubeMapTextureParams(loadMipmap);
texture.isReady = true;
texture.onLoadedObservable.notifyObservers(texture);
texture.onLoadedObservable.clear();
if (onLoad) {
onLoad();
}
};
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
_KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
if (_Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"].IsValid(data)) {
// Need to invert vScale as invertY via UNPACK_FLIP_Y_WEBGL is not supported by compressed texture
texture._invertVScale = !texture.invertY;
var ktx_1 = new _Misc_khronosTextureContainer__WEBPACK_IMPORTED_MODULE_0__["KhronosTextureContainer"](data, 1);
callback(ktx_1.pixelWidth, ktx_1.pixelHeight, texture.generateMipMaps, true, function () {
ktx_1.uploadLevels(texture, texture.generateMipMaps);
}, ktx_1.isInvalid);
}
else if (_Misc_khronosTextureContainer2__WEBPACK_IMPORTED_MODULE_1__["KhronosTextureContainer2"].IsValid(data)) {
var ktx2 = new _Misc_khronosTextureContainer2__WEBPACK_IMPORTED_MODULE_1__["KhronosTextureContainer2"](texture.getEngine());
ktx2.uploadAsync(data, texture).then(function () {
callback(texture.width, texture.height, false, true, function () { }, false);
}, function (error) {
_Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Warn("Failed to load KTX2 texture data: " + error.message);
callback(0, 0, false, false, function () { }, true);
});
}
else {
_Misc_logger__WEBPACK_IMPORTED_MODULE_4__["Logger"].Error("texture missing KTX identifier");
callback(0, 0, false, false, function () { }, true);
}
};
return _KTXTextureLoader;
}());
// Register the loader.
_Engines_engine__WEBPACK_IMPORTED_MODULE_2__["Engine"]._TextureLoaders.unshift(new _KTXTextureLoader());
/***/ }),
/***/ "./Materials/Textures/Loaders/tgaTextureLoader.ts":
/*!********************************************************!*\
!*** ./Materials/Textures/Loaders/tgaTextureLoader.ts ***!
\********************************************************/
/*! exports provided: _TGATextureLoader */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_TGATextureLoader", function() { return _TGATextureLoader; });
/* harmony import */ var _Misc_tga__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Misc/tga */ "./Misc/tga.ts");
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Misc_stringTools__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../Misc/stringTools */ "./Misc/stringTools.ts");
/**
* Implementation of the TGA Texture Loader.
* @hidden
*/
var _TGATextureLoader = /** @class */ (function () {
function _TGATextureLoader() {
/**
* Defines wether the loader supports cascade loading the different faces.
*/
this.supportCascades = false;
}
/**
* This returns if the loader support the current file information.
* @param extension defines the file extension of the file being loaded
* @returns true if the loader can load the specified file
*/
_TGATextureLoader.prototype.canLoad = function (extension) {
return _Misc_stringTools__WEBPACK_IMPORTED_MODULE_2__["StringTools"].EndsWith(extension, ".tga");
};
/**
* Uploads the cube texture data to the WebGL texture. It has already been bound.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param createPolynomials will be true if polynomials have been requested
* @param onLoad defines the callback to trigger once the texture is ready
* @param onError defines the callback to trigger in case of error
*/
_TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
throw ".env not supported in Cube.";
};
/**
* Uploads the 2D texture data to the WebGL texture. It has already been bound once in the callback.
* @param data contains the texture data
* @param texture defines the BabylonJS internal texture
* @param callback defines the method to call once ready to upload
*/
_TGATextureLoader.prototype.loadData = function (data, texture, callback) {
var bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
var header = _Misc_tga__WEBPACK_IMPORTED_MODULE_0__["TGATools"].GetTGAHeader(bytes);
callback(header.width, header.height, texture.generateMipMaps, false, function () {
_Misc_tga__WEBPACK_IMPORTED_MODULE_0__["TGATools"].UploadContent(texture, bytes);
});
};
return _TGATextureLoader;
}());
// Register the loader.
_Engines_engine__WEBPACK_IMPORTED_MODULE_1__["Engine"]._TextureLoaders.push(new _TGATextureLoader());
/***/ }),
/***/ "./Materials/Textures/MultiviewRenderTarget.ts":
/*!*****************************************************!*\
!*** ./Materials/Textures/MultiviewRenderTarget.ts ***!
\*****************************************************/
/*! exports provided: MultiviewRenderTarget */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MultiviewRenderTarget", function() { return MultiviewRenderTarget; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
/* harmony import */ var _Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../Textures/renderTargetTexture */ "./Materials/Textures/renderTargetTexture.ts");
/* harmony import */ var _Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../Textures/internalTexture */ "./Materials/Textures/internalTexture.ts");
/* harmony import */ var _Engines_constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../Engines/constants */ "./Engines/constants.ts");
/**
* Renders to multiple views with a single draw call
* @see https://www.khronos.org/registry/webgl/extensions/WEBGL_multiview/
*/
var MultiviewRenderTarget = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MultiviewRenderTarget, _super);
/**
* Creates a multiview render target
* @param scene scene used with the render target
* @param size the size of the render target (used for each view)
*/
function MultiviewRenderTarget(scene, size) {
if (size === void 0) { size = 512; }
var _this = _super.call(this, "multiview rtt", size, scene, false, true, _Textures_internalTexture__WEBPACK_IMPORTED_MODULE_2__["InternalTextureSource"].Unknown, false, undefined, false, false, true, undefined, true) || this;
var internalTexture = scene.getEngine().createMultiviewRenderTargetTexture(_this.getRenderWidth(), _this.getRenderHeight());
internalTexture.isMultiview = true;
internalTexture.format = _Engines_constants__WEBPACK_IMPORTED_MODULE_3__["Constants"].TEXTUREFORMAT_RGBA;
_this._texture = internalTexture;
_this.samples = _this._getEngine().getCaps().maxSamples || _this.samples;
return _this;
}
/**
* @hidden
* @param faceIndex the face index, if its a cube texture
*/
MultiviewRenderTarget.prototype._bindFrameBuffer = function (faceIndex) {
if (faceIndex === void 0) { faceIndex = 0; }
if (!this._texture) {
return;
}
this.getScene().getEngine().bindMultiviewFramebuffer(this._texture);
};
/**
* Gets the number of views the corresponding to the texture (eg. a MultiviewRenderTarget will have > 1)
* @returns the view count
*/
MultiviewRenderTarget.prototype.getViewCount = function () {
return 2;
};
return MultiviewRenderTarget;
}(_Textures_renderTargetTexture__WEBPACK_IMPORTED_MODULE_1__["RenderTargetTexture"]));
/***/ }),
/***/ "./Materials/Textures/Packer/frame.ts":
/*!********************************************!*\
!*** ./Materials/Textures/Packer/frame.ts ***!
\********************************************/
/*! exports provided: TexturePackerFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TexturePackerFrame", function() { return TexturePackerFrame; });
/**
* This is a support class for frame Data on texture packer sets.
*/
var TexturePackerFrame = /** @class */ (function () {
/**
* Initializes a texture package frame.
* @param id The numerical frame identifier
* @param scale Scalar Vector2 for UV frame
* @param offset Vector2 for the frame position in UV units.
* @returns TexturePackerFrame
*/
function TexturePackerFrame(id, scale, offset) {
this.id = id;
this.scale = scale;
this.offset = offset;
}
return TexturePackerFrame;
}());
/***/ }),
/***/ "./Materials/Textures/Packer/index.ts":
/*!********************************************!*\
!*** ./Materials/Textures/Packer/index.ts ***!
\********************************************/
/*! exports provided: TexturePacker, TexturePackerFrame */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _packer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./packer */ "./Materials/Textures/Packer/packer.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TexturePacker", function() { return _packer__WEBPACK_IMPORTED_MODULE_0__["TexturePacker"]; });
/* harmony import */ var _frame__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./frame */ "./Materials/Textures/Packer/frame.ts");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "TexturePackerFrame", function() { return _frame__WEBPACK_IMPORTED_MODULE_1__["TexturePackerFrame"]; });
/***/ }),
/***/ "./Materials/Textures/Packer/packer.ts":
/*!*********************************************!*\
!*** ./Materials/Textures/Packer/packer.ts ***!
\*********************************************/
/*! exports provided: TexturePacker */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TexturePacker", function() { return TexturePacker; });
/* harmony import */ var _Engines_engine__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../../Engines/engine */ "./Engines/engine.ts");
/* harmony import */ var _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../../Meshes/buffer */ "./Meshes/buffer.ts");
/* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../texture */ "./Materials/Textures/texture.ts");
/* harmony import */ var _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../dynamicTexture */ "./Materials/Textures/dynamicTexture.ts");
/* harmony import */ var _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../../Maths/math.vector */ "./Maths/math.vector.ts");
/* harmony import */ var _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ../../../Maths/math.color */ "./Maths/math.color.ts");
/* harmony import */ var _frame__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./frame */ "./Materials/Textures/Packer/frame.ts");
/* harmony import */ var _Misc_logger__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ../../../Misc/logger */ "./Misc/logger.ts");
/* harmony import */ var _Misc_tools__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! ../../../Misc/tools */ "./Misc/tools.ts");
/**
* This is a support class that generates a series of packed texture sets.
* @see https://doc.babylonjs.com/babylon101/materials
*/
var TexturePacker = /** @class */ (function () {
/**
* Initializes a texture package series from an array of meshes or a single mesh.
* @param name The name of the package
* @param meshes The target meshes to compose the package from
* @param options The arguments that texture packer should follow while building.
* @param scene The scene which the textures are scoped to.
* @returns TexturePacker
*/
function TexturePacker(name, meshes, options, scene) {
var _b, _c, _d, _e, _g, _h, _j, _k, _l, _m, _o, _p, _q;
this.name = name;
this.meshes = meshes;
this.scene = scene;
/**
* Run through the options and set what ever defaults are needed that where not declared.
*/
this.options = options;
this.options.map = (_b = this.options.map) !== null && _b !== void 0 ? _b : [
'ambientTexture',
'bumpTexture',
'diffuseTexture',
'emissiveTexture',
'lightmapTexture',
'opacityTexture',
'reflectionTexture',
'refractionTexture',
'specularTexture'
];
this.options.uvsIn = (_c = this.options.uvsIn) !== null && _c !== void 0 ? _c : _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind;
this.options.uvsOut = (_d = this.options.uvsOut) !== null && _d !== void 0 ? _d : _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind;
this.options.layout = (_e = this.options.layout) !== null && _e !== void 0 ? _e : TexturePacker.LAYOUT_STRIP;
if (this.options.layout === TexturePacker.LAYOUT_COLNUM) {
this.options.colnum = (_g = this.options.colnum) !== null && _g !== void 0 ? _g : 8;
}
this.options.updateInputMeshes = (_h = this.options.updateInputMeshes) !== null && _h !== void 0 ? _h : true;
this.options.disposeSources = (_j = this.options.disposeSources) !== null && _j !== void 0 ? _j : true;
this._expecting = 0;
this.options.fillBlanks = (_k = this.options.fillBlanks) !== null && _k !== void 0 ? _k : true;
if (this.options.fillBlanks === true) {
this.options.customFillColor = (_l = this.options.customFillColor) !== null && _l !== void 0 ? _l : 'black';
}
this.options.frameSize = (_m = this.options.frameSize) !== null && _m !== void 0 ? _m : 256;
this.options.paddingRatio = (_o = this.options.paddingRatio) !== null && _o !== void 0 ? _o : 0.0115;
this._paddingValue = Math.ceil(this.options.frameSize * this.options.paddingRatio);
//Make it an even padding Number.
if (this._paddingValue % 2 !== 0) {
this._paddingValue++;
}
this.options.paddingMode = (_p = this.options.paddingMode) !== null && _p !== void 0 ? _p : TexturePacker.SUBUV_WRAP;
if (this.options.paddingMode === TexturePacker.SUBUV_COLOR) {
this.options.paddingColor = (_q = this.options.paddingColor) !== null && _q !== void 0 ? _q : new _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__["Color4"](0, 0, 0, 1.0);
}
this.sets = {};
this.frames = [];
return this;
}
/**
* Starts the package process
* @param resolve The promises resolution function
* @returns TexturePacker
*/
TexturePacker.prototype._createFrames = function (resolve) {
var _this = this;
var dtSize = this._calculateSize();
var dtUnits = (new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](1, 1)).divide(dtSize);
var doneCount = 0;
var expecting = this._expecting;
var meshLength = this.meshes.length;
var sKeys = Object.keys(this.sets);
for (var i = 0; i < sKeys.length; i++) {
var setName = sKeys[i];
var dt = new _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__["DynamicTexture"](this.name + '.TexturePack.' + setName + 'Set', { width: dtSize.x, height: dtSize.y }, this.scene, true, //Generate Mips
_texture__WEBPACK_IMPORTED_MODULE_2__["Texture"].TRILINEAR_SAMPLINGMODE, _Engines_engine__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTUREFORMAT_RGBA);
var dtx = dt.getContext();
dtx.fillStyle = 'rgba(0,0,0,0)';
dtx.fillRect(0, 0, dtSize.x, dtSize.y);
dt.update(false);
this.sets[setName] = dt;
}
var baseSize = this.options.frameSize || 256;
var padding = this._paddingValue;
var tcs = baseSize + (2 * padding);
var done = function () {
_this._calculateMeshUVFrames(baseSize, padding, dtSize, dtUnits, _this.options.updateInputMeshes || false);
};
//Update the Textures
for (var i = 0; i < meshLength; i++) {
var m = this.meshes[i];
var mat = m.material;
var _loop_1 = function (j) {
var tempTexture = new _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__["DynamicTexture"]('temp', tcs, this_1.scene, true);
var tcx = tempTexture.getContext();
var offset = this_1._getFrameOffset(i);
var updateDt = function () {
doneCount++;
tempTexture.update(false);
var iDat = tcx.getImageData(0, 0, tcs, tcs);
//Update Set
var dt = _this.sets[setName];
var dtx = dt.getContext();
dtx.putImageData(iDat, dtSize.x * offset.x, dtSize.y * offset.y);
tempTexture.dispose();
dt.update(false);
if (doneCount == expecting) {
done();
resolve();
return;
}
};
var setName = sKeys[j] || '_blank';
if (!mat || mat[setName] === null) {
tcx.fillStyle = 'rgba(0,0,0,0)';
if (this_1.options.fillBlanks) {
tcx.fillStyle = this_1.options.customFillColor;
}
tcx.fillRect(0, 0, tcs, tcs);
updateDt();
}
else {
var setTexture = mat[setName];
var img_1 = new Image();
if (setTexture instanceof _dynamicTexture__WEBPACK_IMPORTED_MODULE_3__["DynamicTexture"]) {
img_1.src = setTexture.getContext().canvas.toDataURL("image/png");
}
else {
img_1.src = setTexture.url;
}
_Misc_tools__WEBPACK_IMPORTED_MODULE_8__["Tools"].SetCorsBehavior(img_1.src, img_1);
img_1.onload = function () {
tcx.fillStyle = 'rgba(0,0,0,0)';
tcx.fillRect(0, 0, tcs, tcs);
tempTexture.update(false);
tcx.setTransform(1, 0, 0, -1, 0, 0);
var cellOffsets = [0, 0, 1, 0, 1, 1, 0, 1, -1, 1, -1, 0, -1 - 1, 0, -1, 1, -1];
switch (_this.options.paddingMode) {
//Wrap Mode
case 0:
for (var i_1 = 0; i_1 < 9; i_1++) {
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, (padding) + (baseSize * cellOffsets[i_1]), ((padding) + (baseSize * cellOffsets[i_1 + 1])) - tcs, baseSize, baseSize);
}
break;
//Extend Mode
case 1:
for (var i_2 = 0; i_2 < padding; i_2++) {
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, i_2 + (baseSize * cellOffsets[0]), padding - tcs, baseSize, baseSize);
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, (padding * 2) - i_2, padding - tcs, baseSize, baseSize);
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, padding, i_2 - tcs, baseSize, baseSize);
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, padding, (padding * 2) - i_2 - tcs, baseSize, baseSize);
}
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, (padding) + (baseSize * cellOffsets[0]), ((padding) + (baseSize * cellOffsets[1])) - tcs, baseSize, baseSize);
break;
//Color Mode
case 2:
tcx.fillStyle = (_this.options.paddingColor || _Maths_math_color__WEBPACK_IMPORTED_MODULE_5__["Color3"].Black()).toHexString();
tcx.fillRect(0, 0, tcs, -tcs);
tcx.clearRect(padding, padding, baseSize, baseSize);
tcx.drawImage(img_1, 0, 0, img_1.width, img_1.height, (padding) + (baseSize * cellOffsets[0]), ((padding) + (baseSize * cellOffsets[1])) - tcs, baseSize, baseSize);
break;
}
tcx.setTransform(1, 0, 0, 1, 0, 0);
updateDt();
};
}
};
var this_1 = this;
//Check if the material has the texture
//Create a temporary canvas the same size as 1 frame
//Then apply the texture to the center and the 8 offsets
//Copy the Context and place in the correct frame on the DT
for (var j = 0; j < sKeys.length; j++) {
_loop_1(j);
}
}
};
/**
* Calculates the Size of the Channel Sets
* @returns Vector2
*/
TexturePacker.prototype._calculateSize = function () {
var meshLength = this.meshes.length || 0;
var baseSize = this.options.frameSize || 0;
var padding = this._paddingValue || 0;
switch (this.options.layout) {
case 0:
//STRIP_LAYOUT
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"]((baseSize * meshLength) + (2 * padding * meshLength), (baseSize) + (2 * padding));
break;
case 1:
//POWER2
var sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));
var size = (baseSize * sqrtCount) + (2 * padding * sqrtCount);
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](size, size);
break;
case 2:
//COLNUM
var cols = this.options.colnum || 1;
var rowCnt = Math.max(1, Math.ceil(meshLength / cols));
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"]((baseSize * cols) + (2 * padding * cols), (baseSize * rowCnt) + (2 * padding * rowCnt));
break;
}
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"].Zero();
};
/**
* Calculates the UV data for the frames.
* @param baseSize the base frameSize
* @param padding the base frame padding
* @param dtSize size of the Dynamic Texture for that channel
* @param dtUnits is 1/dtSize
* @param update flag to update the input meshes
*/
TexturePacker.prototype._calculateMeshUVFrames = function (baseSize, padding, dtSize, dtUnits, update) {
var meshLength = this.meshes.length;
for (var i = 0; i < meshLength; i++) {
var m = this.meshes[i];
var scale = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](baseSize / dtSize.x, baseSize / dtSize.y);
var pOffset = dtUnits.clone().scale(padding);
var frameOffset = this._getFrameOffset(i);
var offset = frameOffset.add(pOffset);
var frame = new _frame__WEBPACK_IMPORTED_MODULE_6__["TexturePackerFrame"](i, scale, offset);
this.frames.push(frame);
//Update Output UVs
if (update) {
this._updateMeshUV(m, i);
this._updateTextureReferences(m);
}
}
};
/**
* Calculates the frames Offset.
* @param index of the frame
* @returns Vector2
*/
TexturePacker.prototype._getFrameOffset = function (index) {
var meshLength = this.meshes.length;
var uvStep, yStep, xStep;
switch (this.options.layout) {
case 0:
//STRIP_LAYOUT
uvStep = 1 / meshLength;
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](index * uvStep, 0);
break;
case 1:
//POWER2
var sqrtCount = Math.max(2, Math.ceil(Math.sqrt(meshLength)));
yStep = Math.floor(index / sqrtCount);
xStep = index - (yStep * sqrtCount);
uvStep = 1 / sqrtCount;
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](xStep * uvStep, yStep * uvStep);
break;
case 2:
//COLNUM
var cols = this.options.colnum || 1;
var rowCnt = Math.max(1, Math.ceil(meshLength / cols));
xStep = Math.floor(index / rowCnt);
yStep = index - (xStep * rowCnt);
uvStep = new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](1 / cols, 1 / rowCnt);
return new _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"](xStep * uvStep.x, yStep * uvStep.y);
break;
}
return _Maths_math_vector__WEBPACK_IMPORTED_MODULE_4__["Vector2"].Zero();
};
/**
* Updates a Mesh to the frame data
* @param mesh that is the target
* @param frameID or the frame index
*/
TexturePacker.prototype._updateMeshUV = function (mesh, frameID) {
var frame = this.frames[frameID];
var uvIn = mesh.getVerticesData(this.options.uvsIn || _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind);
var uvOut = [];
var toCount = 0;
if (uvIn.length) {
toCount = uvIn.length || 0;
}
for (var i = 0; i < toCount; i += 2) {
uvOut.push((uvIn[i] * frame.scale.x) + frame.offset.x, (uvIn[i + 1] * frame.scale.y) + frame.offset.y);
}
mesh.setVerticesData(this.options.uvsOut || _Meshes_buffer__WEBPACK_IMPORTED_MODULE_1__["VertexBuffer"].UVKind, uvOut);
};
/**
* Updates a Meshes materials to use the texture packer channels
* @param m is the mesh to target
* @param force all channels on the packer to be set.
*/
TexturePacker.prototype._updateTextureReferences = function (m, force) {
if (force === void 0) { force = false; }
var mat = m.material;
var sKeys = Object.keys(this.sets);
var _dispose = function (_t) {
if ((_t.dispose)) {
_t.dispose();
}
};
for (var i = 0; i < sKeys.length; i++) {
var setName = sKeys[i];
if (!force) {
if (!mat) {
return;
}
if (mat[setName] !== null) {
_dispose(mat[setName]);
mat[setName] = this.sets[setName];
}
}
else {
if (mat[setName] !== null) {
_dispose(mat[setName]);
}
mat[setName] = this.sets[setName];
}
}
};
/**
* Public method to set a Mesh to a frame
* @param m that is the target
* @param frameID or the frame index
* @param updateMaterial trigger for if the Meshes attached Material be updated?
*/
TexturePacker.prototype.setMeshToFrame = function (m, frameID, updateMaterial) {
if (updateMaterial === void 0) { updateMaterial = false; }
this._updateMeshUV(m, frameID);
if (updateMaterial) {
this._updateTextureReferences(m, true);
}
};
/**
* Starts the async promise to compile the texture packer.
* @returns Promise